MySQL: Select max from group using the value from a different table?Insert into … values ( SELECT … FROM … )Add a column with a default value to an existing table in SQL ServerRetrieving the last record in each group - MySQLSQL Server: How to Join to first rowHow do I UPDATE from a SELECT in SQL Server?Finding duplicate values in a SQL tableSelect first row in each GROUP BY group?What are the options for storing hierarchical data in a relational database?SQL select only rows with max value on a columnGet records with max value for each group of grouped SQL results

Is it possible to play as a necromancer skeleton?

Installed Tankless Water Heater - Internet loss when active

Should breaking down something like a door be adjudicated as an attempt to beat its AC and HP, or as an ability check against a set DC?

Why do most published works in medical imaging try to reduce false positives?

How to patch glass cuts in a bicycle tire?

Caught 2 students cheating together on the final exam that I proctored

using Leibniz rule to solve definite integral

Why is this Simple Puzzle impossible to solve?

Pirate democracy at its finest

Python program to take in two strings and print the larger string

Can I tell a prospective employee that everyone in the team is leaving?

Why would Ryanair allow me to book this journey through a third party, but not through their own website?

What is the object moving across the ceiling in this stock footage?

Why didn't Project Mercury advance to an orbital flight on their second mission?

Looking for a soft substance that doesn't dissolve underwater

A steel cutting sword?

Is it rude to call a professor by their last name with no prefix in a non-academic setting?

How to know if a folder is a symbolic link?

Website returning plaintext password

Is the Indo-European language family made up?

Sitecore 9.0 works with solr 7.2.1?

High resistance, no current. What's the point of a potential then?

NIntegrate doesn't evaluate

USPS Back Room - Trespassing?



MySQL: Select max from group using the value from a different table?


Insert into … values ( SELECT … FROM … )Add a column with a default value to an existing table in SQL ServerRetrieving the last record in each group - MySQLSQL Server: How to Join to first rowHow do I UPDATE from a SELECT in SQL Server?Finding duplicate values in a SQL tableSelect first row in each GROUP BY group?What are the options for storing hierarchical data in a relational database?SQL select only rows with max value on a columnGet records with max value for each group of grouped SQL results






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I have two tables, and I'm trying to find the max value of a column in the first table grouped by a column in the second table.



Here's an example of what I mean:



table customers:



customer_id | age
12367 | 23
87693 | 48
66933 | 44
82143 | 38
75454 | 19
38912 | 58
63554 | 80


table purchases:



product_id | customer_id
132 | 12367
132 | 66933
132 | 38912
844 | 12367
844 | 63554
598 | 75454
598 | 87693
598 | 66933


I want to find the customer_id of the oldest purchaser of each product, e.g.:



product_id | customer_id | age
132 | 38912 | 58
844 | 63554 | 80
598 | 87693 | 48


How would I create an mysql query to find this?










share|improve this question




























    1















    I have two tables, and I'm trying to find the max value of a column in the first table grouped by a column in the second table.



    Here's an example of what I mean:



    table customers:



    customer_id | age
    12367 | 23
    87693 | 48
    66933 | 44
    82143 | 38
    75454 | 19
    38912 | 58
    63554 | 80


    table purchases:



    product_id | customer_id
    132 | 12367
    132 | 66933
    132 | 38912
    844 | 12367
    844 | 63554
    598 | 75454
    598 | 87693
    598 | 66933


    I want to find the customer_id of the oldest purchaser of each product, e.g.:



    product_id | customer_id | age
    132 | 38912 | 58
    844 | 63554 | 80
    598 | 87693 | 48


    How would I create an mysql query to find this?










    share|improve this question
























      1












      1








      1








      I have two tables, and I'm trying to find the max value of a column in the first table grouped by a column in the second table.



      Here's an example of what I mean:



      table customers:



      customer_id | age
      12367 | 23
      87693 | 48
      66933 | 44
      82143 | 38
      75454 | 19
      38912 | 58
      63554 | 80


      table purchases:



      product_id | customer_id
      132 | 12367
      132 | 66933
      132 | 38912
      844 | 12367
      844 | 63554
      598 | 75454
      598 | 87693
      598 | 66933


      I want to find the customer_id of the oldest purchaser of each product, e.g.:



      product_id | customer_id | age
      132 | 38912 | 58
      844 | 63554 | 80
      598 | 87693 | 48


      How would I create an mysql query to find this?










      share|improve this question














      I have two tables, and I'm trying to find the max value of a column in the first table grouped by a column in the second table.



      Here's an example of what I mean:



      table customers:



      customer_id | age
      12367 | 23
      87693 | 48
      66933 | 44
      82143 | 38
      75454 | 19
      38912 | 58
      63554 | 80


      table purchases:



      product_id | customer_id
      132 | 12367
      132 | 66933
      132 | 38912
      844 | 12367
      844 | 63554
      598 | 75454
      598 | 87693
      598 | 66933


      I want to find the customer_id of the oldest purchaser of each product, e.g.:



      product_id | customer_id | age
      132 | 38912 | 58
      844 | 63554 | 80
      598 | 87693 | 48


      How would I create an mysql query to find this?







      mysql sql






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 24 at 3:51









      16jacobj16jacobj

      386




      386






















          1 Answer
          1






          active

          oldest

          votes


















          1














          use correlated subquery



          select product_id , a.customer_id , age
          from purchases a inner join customers b on a.customer_id =b.customer_id
          where age in (select max(age) from purchases a1 inner join customers b1 on a1.customer_id =b1.customer_id where a.product_id=a1.product_id group by a1.product_id)





          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%2f55320576%2fmysql-select-max-from-group-using-the-value-from-a-different-table%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            use correlated subquery



            select product_id , a.customer_id , age
            from purchases a inner join customers b on a.customer_id =b.customer_id
            where age in (select max(age) from purchases a1 inner join customers b1 on a1.customer_id =b1.customer_id where a.product_id=a1.product_id group by a1.product_id)





            share|improve this answer



























              1














              use correlated subquery



              select product_id , a.customer_id , age
              from purchases a inner join customers b on a.customer_id =b.customer_id
              where age in (select max(age) from purchases a1 inner join customers b1 on a1.customer_id =b1.customer_id where a.product_id=a1.product_id group by a1.product_id)





              share|improve this answer

























                1












                1








                1







                use correlated subquery



                select product_id , a.customer_id , age
                from purchases a inner join customers b on a.customer_id =b.customer_id
                where age in (select max(age) from purchases a1 inner join customers b1 on a1.customer_id =b1.customer_id where a.product_id=a1.product_id group by a1.product_id)





                share|improve this answer













                use correlated subquery



                select product_id , a.customer_id , age
                from purchases a inner join customers b on a.customer_id =b.customer_id
                where age in (select max(age) from purchases a1 inner join customers b1 on a1.customer_id =b1.customer_id where a.product_id=a1.product_id group by a1.product_id)






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 24 at 4:04









                fa06fa06

                21.5k41019




                21.5k41019



























                    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.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55320576%2fmysql-select-max-from-group-using-the-value-from-a-different-table%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

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                    Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript