Retrieve only one record from LEFT JOIN










0














I have two tables that one stores advertisements (ads) and other stores images (images). images usually contain more than one images per each records in ads.



ads table



+------------+------------+
|ad_id |title |
+------------+------------+
|1 |sample1 |
+------------+------------+
|2 |sample2 |
+------------+------------+


images table



+------------+------------+
|image_id |image |
+------------+------------+
|1 |1.jpg |
+------------+------------+
|1 |2.jpg |
+------------+------------+
|2 |3.jpg |
+------------+------------+


What I want to do is make a list of ads with one image per each record in ads and currently using following sql query.



SELECT a.`title`, i.`image`
FROM ads a
LEFT JOIN `images` i ON i.`id` = a.`id`


but this returns me three records instead of two ads, which contains duplicate records from ads as images contains two records of images.



How do I limit only one image per one record in the ads.



Any help would be really appreciated. TIA



PS:
current output is like



sample1, 1.jpg
sample1, 2.jpg
sample2, 3.jpg


But I'm expecting



sample1, 1.jpg
sample2, 3.jpg


or



sample1, 2.jpg
sample2, 3.jpg









share|improve this question



















  • 1




    What's your dbms? and your expect result?
    – D-Shih
    Nov 10 at 3:07






  • 1




    Because there are two image_id= 1 rows in images table
    – D-Shih
    Nov 10 at 3:09











  • Hi. This is a faq. Please always google many clear, concise & specific versions/phrasings of your question/problem/goal with & without your particular strings/names & read many answers. Add relevant keywords you discover to your searches. If you don't find an answer then post, using 1 variant search as title & keywords for tags. See the downvote arrow mouseover text. When you do have a non-duplicate code question to post please read & act on Minimal, Complete, and Verifiable example.
    – philipxy
    Nov 10 at 6:38















0














I have two tables that one stores advertisements (ads) and other stores images (images). images usually contain more than one images per each records in ads.



ads table



+------------+------------+
|ad_id |title |
+------------+------------+
|1 |sample1 |
+------------+------------+
|2 |sample2 |
+------------+------------+


images table



+------------+------------+
|image_id |image |
+------------+------------+
|1 |1.jpg |
+------------+------------+
|1 |2.jpg |
+------------+------------+
|2 |3.jpg |
+------------+------------+


What I want to do is make a list of ads with one image per each record in ads and currently using following sql query.



SELECT a.`title`, i.`image`
FROM ads a
LEFT JOIN `images` i ON i.`id` = a.`id`


but this returns me three records instead of two ads, which contains duplicate records from ads as images contains two records of images.



How do I limit only one image per one record in the ads.



Any help would be really appreciated. TIA



PS:
current output is like



sample1, 1.jpg
sample1, 2.jpg
sample2, 3.jpg


But I'm expecting



sample1, 1.jpg
sample2, 3.jpg


or



sample1, 2.jpg
sample2, 3.jpg









share|improve this question



















  • 1




    What's your dbms? and your expect result?
    – D-Shih
    Nov 10 at 3:07






  • 1




    Because there are two image_id= 1 rows in images table
    – D-Shih
    Nov 10 at 3:09











  • Hi. This is a faq. Please always google many clear, concise & specific versions/phrasings of your question/problem/goal with & without your particular strings/names & read many answers. Add relevant keywords you discover to your searches. If you don't find an answer then post, using 1 variant search as title & keywords for tags. See the downvote arrow mouseover text. When you do have a non-duplicate code question to post please read & act on Minimal, Complete, and Verifiable example.
    – philipxy
    Nov 10 at 6:38













0












0








0


1





I have two tables that one stores advertisements (ads) and other stores images (images). images usually contain more than one images per each records in ads.



ads table



+------------+------------+
|ad_id |title |
+------------+------------+
|1 |sample1 |
+------------+------------+
|2 |sample2 |
+------------+------------+


images table



+------------+------------+
|image_id |image |
+------------+------------+
|1 |1.jpg |
+------------+------------+
|1 |2.jpg |
+------------+------------+
|2 |3.jpg |
+------------+------------+


What I want to do is make a list of ads with one image per each record in ads and currently using following sql query.



SELECT a.`title`, i.`image`
FROM ads a
LEFT JOIN `images` i ON i.`id` = a.`id`


but this returns me three records instead of two ads, which contains duplicate records from ads as images contains two records of images.



How do I limit only one image per one record in the ads.



Any help would be really appreciated. TIA



PS:
current output is like



sample1, 1.jpg
sample1, 2.jpg
sample2, 3.jpg


But I'm expecting



sample1, 1.jpg
sample2, 3.jpg


or



sample1, 2.jpg
sample2, 3.jpg









share|improve this question















I have two tables that one stores advertisements (ads) and other stores images (images). images usually contain more than one images per each records in ads.



ads table



+------------+------------+
|ad_id |title |
+------------+------------+
|1 |sample1 |
+------------+------------+
|2 |sample2 |
+------------+------------+


images table



+------------+------------+
|image_id |image |
+------------+------------+
|1 |1.jpg |
+------------+------------+
|1 |2.jpg |
+------------+------------+
|2 |3.jpg |
+------------+------------+


What I want to do is make a list of ads with one image per each record in ads and currently using following sql query.



SELECT a.`title`, i.`image`
FROM ads a
LEFT JOIN `images` i ON i.`id` = a.`id`


but this returns me three records instead of two ads, which contains duplicate records from ads as images contains two records of images.



How do I limit only one image per one record in the ads.



Any help would be really appreciated. TIA



PS:
current output is like



sample1, 1.jpg
sample1, 2.jpg
sample2, 3.jpg


But I'm expecting



sample1, 1.jpg
sample2, 3.jpg


or



sample1, 2.jpg
sample2, 3.jpg






sql join group-by aggregate-functions






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 10 at 3:20









D-Shih

25.4k61431




25.4k61431










asked Nov 10 at 2:48









AmilaDG

1061314




1061314







  • 1




    What's your dbms? and your expect result?
    – D-Shih
    Nov 10 at 3:07






  • 1




    Because there are two image_id= 1 rows in images table
    – D-Shih
    Nov 10 at 3:09











  • Hi. This is a faq. Please always google many clear, concise & specific versions/phrasings of your question/problem/goal with & without your particular strings/names & read many answers. Add relevant keywords you discover to your searches. If you don't find an answer then post, using 1 variant search as title & keywords for tags. See the downvote arrow mouseover text. When you do have a non-duplicate code question to post please read & act on Minimal, Complete, and Verifiable example.
    – philipxy
    Nov 10 at 6:38












  • 1




    What's your dbms? and your expect result?
    – D-Shih
    Nov 10 at 3:07






  • 1




    Because there are two image_id= 1 rows in images table
    – D-Shih
    Nov 10 at 3:09











  • Hi. This is a faq. Please always google many clear, concise & specific versions/phrasings of your question/problem/goal with & without your particular strings/names & read many answers. Add relevant keywords you discover to your searches. If you don't find an answer then post, using 1 variant search as title & keywords for tags. See the downvote arrow mouseover text. When you do have a non-duplicate code question to post please read & act on Minimal, Complete, and Verifiable example.
    – philipxy
    Nov 10 at 6:38







1




1




What's your dbms? and your expect result?
– D-Shih
Nov 10 at 3:07




What's your dbms? and your expect result?
– D-Shih
Nov 10 at 3:07




1




1




Because there are two image_id= 1 rows in images table
– D-Shih
Nov 10 at 3:09





Because there are two image_id= 1 rows in images table
– D-Shih
Nov 10 at 3:09













Hi. This is a faq. Please always google many clear, concise & specific versions/phrasings of your question/problem/goal with & without your particular strings/names & read many answers. Add relevant keywords you discover to your searches. If you don't find an answer then post, using 1 variant search as title & keywords for tags. See the downvote arrow mouseover text. When you do have a non-duplicate code question to post please read & act on Minimal, Complete, and Verifiable example.
– philipxy
Nov 10 at 6:38




Hi. This is a faq. Please always google many clear, concise & specific versions/phrasings of your question/problem/goal with & without your particular strings/names & read many answers. Add relevant keywords you discover to your searches. If you don't find an answer then post, using 1 variant search as title & keywords for tags. See the downvote arrow mouseover text. When you do have a non-duplicate code question to post please read & act on Minimal, Complete, and Verifiable example.
– philipxy
Nov 10 at 6:38












3 Answers
3






active

oldest

votes


















1














LEFT JOIN means will be on the table which on the left side by the ON condition but it will be all match by id = 1 or id = 2



You can try to use aggregate function MIN or MAX oni.image` column to make your expectation.



If you want to get 1.jpg you can use MIN otherwise use MAX



CREATE TABLE ads(
ad_id INT,
title VARCHAR(50)
);


INSERT INTO ads VALUES (1,'sample1');
INSERT INTO ads VALUES (2,'sample2');

CREATE TABLE images(
image_id INT,
image VARCHAR(50)
);


INSERT INTO images VALUES(1,'1.jpg');
INSERT INTO images VALUES(1,'2.jpg');
INSERT INTO images VALUES(2,'3.jpg');



Query #1



SELECT a.`title`,MIN(i.`image`)
FROM ads a
LEFT JOIN `images` i ON i.`image_id` = a.`ad_id`
GROUP BY a.`title`;

| title | MIN(i.`image`) |
| ------- | -------------- |
| sample1 | 1.jpg |
| sample2 | 3.jpg |



View on DB Fiddle






share|improve this answer






























    1














    The simplest way is probably a correlated subquery:



    SELECT a.title,
    (SELECT i.image
    FROM image` i
    WHERE i.id = a.id
    LIMIT 1
    ) as image
    FROM ads a;


    This returns an arbitrary image. You can add an ORDER BY to the subquery to get a particular image, such as:




    • ORDER BY rand() to get a random image


    • ORDER BY i.id to get the smallest id


    • ORDER BY i.createDate DESC to get the newest one

    • and so on





    share|improve this answer




























      0














      SELECT OG.tittle as Title, 
      OG.image as Image
      FROM
      (
      SELECT a.title as tittle,
      i.image as image,
      row_number() over (Partition BY i.image_id ORDER BY i.image_id ASC ) as rn
      FROM ads a
      LEFT JOIN images i ON i.id = a.id
      ) OG
      WHERE rn =1


      This query will only display one image per one record based on row number based filtering .



      For more info on joins click here https://medium.com/@cdaniel7/run-down-of-sql-joins-434d9d03f2d






      share|improve this answer




















        Your Answer






        StackExchange.ifUsing("editor", function ()
        StackExchange.using("externalEditor", function ()
        StackExchange.using("snippets", function ()
        StackExchange.snippets.init();
        );
        );
        , "code-snippets");

        StackExchange.ready(function()
        var channelOptions =
        tags: "".split(" "),
        id: "1"
        ;
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function()
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled)
        StackExchange.using("snippets", function()
        createEditor();
        );

        else
        createEditor();

        );

        function createEditor()
        StackExchange.prepareEditor(
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader:
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        ,
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        );



        );













        draft saved

        draft discarded


















        StackExchange.ready(
        function ()
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53235609%2fretrieve-only-one-record-from-left-join%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        1














        LEFT JOIN means will be on the table which on the left side by the ON condition but it will be all match by id = 1 or id = 2



        You can try to use aggregate function MIN or MAX oni.image` column to make your expectation.



        If you want to get 1.jpg you can use MIN otherwise use MAX



        CREATE TABLE ads(
        ad_id INT,
        title VARCHAR(50)
        );


        INSERT INTO ads VALUES (1,'sample1');
        INSERT INTO ads VALUES (2,'sample2');

        CREATE TABLE images(
        image_id INT,
        image VARCHAR(50)
        );


        INSERT INTO images VALUES(1,'1.jpg');
        INSERT INTO images VALUES(1,'2.jpg');
        INSERT INTO images VALUES(2,'3.jpg');



        Query #1



        SELECT a.`title`,MIN(i.`image`)
        FROM ads a
        LEFT JOIN `images` i ON i.`image_id` = a.`ad_id`
        GROUP BY a.`title`;

        | title | MIN(i.`image`) |
        | ------- | -------------- |
        | sample1 | 1.jpg |
        | sample2 | 3.jpg |



        View on DB Fiddle






        share|improve this answer



























          1














          LEFT JOIN means will be on the table which on the left side by the ON condition but it will be all match by id = 1 or id = 2



          You can try to use aggregate function MIN or MAX oni.image` column to make your expectation.



          If you want to get 1.jpg you can use MIN otherwise use MAX



          CREATE TABLE ads(
          ad_id INT,
          title VARCHAR(50)
          );


          INSERT INTO ads VALUES (1,'sample1');
          INSERT INTO ads VALUES (2,'sample2');

          CREATE TABLE images(
          image_id INT,
          image VARCHAR(50)
          );


          INSERT INTO images VALUES(1,'1.jpg');
          INSERT INTO images VALUES(1,'2.jpg');
          INSERT INTO images VALUES(2,'3.jpg');



          Query #1



          SELECT a.`title`,MIN(i.`image`)
          FROM ads a
          LEFT JOIN `images` i ON i.`image_id` = a.`ad_id`
          GROUP BY a.`title`;

          | title | MIN(i.`image`) |
          | ------- | -------------- |
          | sample1 | 1.jpg |
          | sample2 | 3.jpg |



          View on DB Fiddle






          share|improve this answer

























            1












            1








            1






            LEFT JOIN means will be on the table which on the left side by the ON condition but it will be all match by id = 1 or id = 2



            You can try to use aggregate function MIN or MAX oni.image` column to make your expectation.



            If you want to get 1.jpg you can use MIN otherwise use MAX



            CREATE TABLE ads(
            ad_id INT,
            title VARCHAR(50)
            );


            INSERT INTO ads VALUES (1,'sample1');
            INSERT INTO ads VALUES (2,'sample2');

            CREATE TABLE images(
            image_id INT,
            image VARCHAR(50)
            );


            INSERT INTO images VALUES(1,'1.jpg');
            INSERT INTO images VALUES(1,'2.jpg');
            INSERT INTO images VALUES(2,'3.jpg');



            Query #1



            SELECT a.`title`,MIN(i.`image`)
            FROM ads a
            LEFT JOIN `images` i ON i.`image_id` = a.`ad_id`
            GROUP BY a.`title`;

            | title | MIN(i.`image`) |
            | ------- | -------------- |
            | sample1 | 1.jpg |
            | sample2 | 3.jpg |



            View on DB Fiddle






            share|improve this answer














            LEFT JOIN means will be on the table which on the left side by the ON condition but it will be all match by id = 1 or id = 2



            You can try to use aggregate function MIN or MAX oni.image` column to make your expectation.



            If you want to get 1.jpg you can use MIN otherwise use MAX



            CREATE TABLE ads(
            ad_id INT,
            title VARCHAR(50)
            );


            INSERT INTO ads VALUES (1,'sample1');
            INSERT INTO ads VALUES (2,'sample2');

            CREATE TABLE images(
            image_id INT,
            image VARCHAR(50)
            );


            INSERT INTO images VALUES(1,'1.jpg');
            INSERT INTO images VALUES(1,'2.jpg');
            INSERT INTO images VALUES(2,'3.jpg');



            Query #1



            SELECT a.`title`,MIN(i.`image`)
            FROM ads a
            LEFT JOIN `images` i ON i.`image_id` = a.`ad_id`
            GROUP BY a.`title`;

            | title | MIN(i.`image`) |
            | ------- | -------------- |
            | sample1 | 1.jpg |
            | sample2 | 3.jpg |



            View on DB Fiddle







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 10 at 3:16

























            answered Nov 10 at 3:11









            D-Shih

            25.4k61431




            25.4k61431























                1














                The simplest way is probably a correlated subquery:



                SELECT a.title,
                (SELECT i.image
                FROM image` i
                WHERE i.id = a.id
                LIMIT 1
                ) as image
                FROM ads a;


                This returns an arbitrary image. You can add an ORDER BY to the subquery to get a particular image, such as:




                • ORDER BY rand() to get a random image


                • ORDER BY i.id to get the smallest id


                • ORDER BY i.createDate DESC to get the newest one

                • and so on





                share|improve this answer

























                  1














                  The simplest way is probably a correlated subquery:



                  SELECT a.title,
                  (SELECT i.image
                  FROM image` i
                  WHERE i.id = a.id
                  LIMIT 1
                  ) as image
                  FROM ads a;


                  This returns an arbitrary image. You can add an ORDER BY to the subquery to get a particular image, such as:




                  • ORDER BY rand() to get a random image


                  • ORDER BY i.id to get the smallest id


                  • ORDER BY i.createDate DESC to get the newest one

                  • and so on





                  share|improve this answer























                    1












                    1








                    1






                    The simplest way is probably a correlated subquery:



                    SELECT a.title,
                    (SELECT i.image
                    FROM image` i
                    WHERE i.id = a.id
                    LIMIT 1
                    ) as image
                    FROM ads a;


                    This returns an arbitrary image. You can add an ORDER BY to the subquery to get a particular image, such as:




                    • ORDER BY rand() to get a random image


                    • ORDER BY i.id to get the smallest id


                    • ORDER BY i.createDate DESC to get the newest one

                    • and so on





                    share|improve this answer












                    The simplest way is probably a correlated subquery:



                    SELECT a.title,
                    (SELECT i.image
                    FROM image` i
                    WHERE i.id = a.id
                    LIMIT 1
                    ) as image
                    FROM ads a;


                    This returns an arbitrary image. You can add an ORDER BY to the subquery to get a particular image, such as:




                    • ORDER BY rand() to get a random image


                    • ORDER BY i.id to get the smallest id


                    • ORDER BY i.createDate DESC to get the newest one

                    • and so on






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 10 at 12:39









                    Gordon Linoff

                    757k35291399




                    757k35291399





















                        0














                        SELECT OG.tittle as Title, 
                        OG.image as Image
                        FROM
                        (
                        SELECT a.title as tittle,
                        i.image as image,
                        row_number() over (Partition BY i.image_id ORDER BY i.image_id ASC ) as rn
                        FROM ads a
                        LEFT JOIN images i ON i.id = a.id
                        ) OG
                        WHERE rn =1


                        This query will only display one image per one record based on row number based filtering .



                        For more info on joins click here https://medium.com/@cdaniel7/run-down-of-sql-joins-434d9d03f2d






                        share|improve this answer

























                          0














                          SELECT OG.tittle as Title, 
                          OG.image as Image
                          FROM
                          (
                          SELECT a.title as tittle,
                          i.image as image,
                          row_number() over (Partition BY i.image_id ORDER BY i.image_id ASC ) as rn
                          FROM ads a
                          LEFT JOIN images i ON i.id = a.id
                          ) OG
                          WHERE rn =1


                          This query will only display one image per one record based on row number based filtering .



                          For more info on joins click here https://medium.com/@cdaniel7/run-down-of-sql-joins-434d9d03f2d






                          share|improve this answer























                            0












                            0








                            0






                            SELECT OG.tittle as Title, 
                            OG.image as Image
                            FROM
                            (
                            SELECT a.title as tittle,
                            i.image as image,
                            row_number() over (Partition BY i.image_id ORDER BY i.image_id ASC ) as rn
                            FROM ads a
                            LEFT JOIN images i ON i.id = a.id
                            ) OG
                            WHERE rn =1


                            This query will only display one image per one record based on row number based filtering .



                            For more info on joins click here https://medium.com/@cdaniel7/run-down-of-sql-joins-434d9d03f2d






                            share|improve this answer












                            SELECT OG.tittle as Title, 
                            OG.image as Image
                            FROM
                            (
                            SELECT a.title as tittle,
                            i.image as image,
                            row_number() over (Partition BY i.image_id ORDER BY i.image_id ASC ) as rn
                            FROM ads a
                            LEFT JOIN images i ON i.id = a.id
                            ) OG
                            WHERE rn =1


                            This query will only display one image per one record based on row number based filtering .



                            For more info on joins click here https://medium.com/@cdaniel7/run-down-of-sql-joins-434d9d03f2d







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 10 at 8:12









                            Christopher Daniel Devairakkam

                            1




                            1



























                                draft saved

                                draft discarded
















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid


                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.

                                To learn more, see our tips on writing great answers.





                                Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                Please pay close attention to the following guidance:


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid


                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.

                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function ()
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53235609%2fretrieve-only-one-record-from-left-join%23new-answer', 'question_page');

                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

                                Edmonton

                                Crossroads (UK TV series)