How to group by product ID with latest creation date in mysql?











up vote
1
down vote

favorite












I have select statement as below and sample output :-



select uph.creation_date, p.name,p.product_id from product p 
left join user_product_history uph on p.product_id = uph.product_id
where uph.user_id = 124 order by uph.creation_date desc


enter image description here



How can I group by product ID with lastest creation date? Please help. Thank you.



Edited with PHP API .model file



// ~/user/product_history
public function product_history($data) {
$sql = 'select uph.creation_date,
p.name,
p.product_id
from product p
join user_product_history uph
on p.product_id = uph.product_id and
uph.user_id = ?
join (select product_id,
MAX(creation_date) AS max_creation_date
from user_product_history
where user_id = ?
group by product_id) dt
on dt.product_id = uph.product_id and
dt.max_creation_date = uph.creation_date
order by uph.creation_date desc';

$result = $this->db->query($sql, array($data['user_id']));
$records = array();
foreach( $result->result_array() as $r ) {
$r['product_id'] = (int) $r['product_id'];
$r['sub_category_id'] = (int) $r['sub_category_id'];
$r['merchant_id'] = (int) $r['merchant_id'];
if (!isset($r['price_discount'])) $r['price_discount'] = '';
$records = $r;
}
return $records;
}









share|improve this question




























    up vote
    1
    down vote

    favorite












    I have select statement as below and sample output :-



    select uph.creation_date, p.name,p.product_id from product p 
    left join user_product_history uph on p.product_id = uph.product_id
    where uph.user_id = 124 order by uph.creation_date desc


    enter image description here



    How can I group by product ID with lastest creation date? Please help. Thank you.



    Edited with PHP API .model file



    // ~/user/product_history
    public function product_history($data) {
    $sql = 'select uph.creation_date,
    p.name,
    p.product_id
    from product p
    join user_product_history uph
    on p.product_id = uph.product_id and
    uph.user_id = ?
    join (select product_id,
    MAX(creation_date) AS max_creation_date
    from user_product_history
    where user_id = ?
    group by product_id) dt
    on dt.product_id = uph.product_id and
    dt.max_creation_date = uph.creation_date
    order by uph.creation_date desc';

    $result = $this->db->query($sql, array($data['user_id']));
    $records = array();
    foreach( $result->result_array() as $r ) {
    $r['product_id'] = (int) $r['product_id'];
    $r['sub_category_id'] = (int) $r['sub_category_id'];
    $r['merchant_id'] = (int) $r['merchant_id'];
    if (!isset($r['price_discount'])) $r['price_discount'] = '';
    $records = $r;
    }
    return $records;
    }









    share|improve this question


























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      I have select statement as below and sample output :-



      select uph.creation_date, p.name,p.product_id from product p 
      left join user_product_history uph on p.product_id = uph.product_id
      where uph.user_id = 124 order by uph.creation_date desc


      enter image description here



      How can I group by product ID with lastest creation date? Please help. Thank you.



      Edited with PHP API .model file



      // ~/user/product_history
      public function product_history($data) {
      $sql = 'select uph.creation_date,
      p.name,
      p.product_id
      from product p
      join user_product_history uph
      on p.product_id = uph.product_id and
      uph.user_id = ?
      join (select product_id,
      MAX(creation_date) AS max_creation_date
      from user_product_history
      where user_id = ?
      group by product_id) dt
      on dt.product_id = uph.product_id and
      dt.max_creation_date = uph.creation_date
      order by uph.creation_date desc';

      $result = $this->db->query($sql, array($data['user_id']));
      $records = array();
      foreach( $result->result_array() as $r ) {
      $r['product_id'] = (int) $r['product_id'];
      $r['sub_category_id'] = (int) $r['sub_category_id'];
      $r['merchant_id'] = (int) $r['merchant_id'];
      if (!isset($r['price_discount'])) $r['price_discount'] = '';
      $records = $r;
      }
      return $records;
      }









      share|improve this question















      I have select statement as below and sample output :-



      select uph.creation_date, p.name,p.product_id from product p 
      left join user_product_history uph on p.product_id = uph.product_id
      where uph.user_id = 124 order by uph.creation_date desc


      enter image description here



      How can I group by product ID with lastest creation date? Please help. Thank you.



      Edited with PHP API .model file



      // ~/user/product_history
      public function product_history($data) {
      $sql = 'select uph.creation_date,
      p.name,
      p.product_id
      from product p
      join user_product_history uph
      on p.product_id = uph.product_id and
      uph.user_id = ?
      join (select product_id,
      MAX(creation_date) AS max_creation_date
      from user_product_history
      where user_id = ?
      group by product_id) dt
      on dt.product_id = uph.product_id and
      dt.max_creation_date = uph.creation_date
      order by uph.creation_date desc';

      $result = $this->db->query($sql, array($data['user_id']));
      $records = array();
      foreach( $result->result_array() as $r ) {
      $r['product_id'] = (int) $r['product_id'];
      $r['sub_category_id'] = (int) $r['sub_category_id'];
      $r['merchant_id'] = (int) $r['merchant_id'];
      if (!isset($r['price_discount'])) $r['price_discount'] = '';
      $records = $r;
      }
      return $records;
      }






      mysql select






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 5 at 7:14

























      asked Nov 5 at 3:52









      henry

      5418




      5418
























          2 Answers
          2






          active

          oldest

          votes

















          up vote
          3
          down vote



          accepted











          • Firstly, you dont need a Left Join here, as you are filtering on user_product_history table also. It does seem like you want to show only those product(s), which has a creation_date corresponding to user_id = 124. So, you can simply use Inner Join instead.

          • In a derived table (sub-select query), determine the maximum value of creation_date for every product_id.

          • Now, use this result-set to join to the main tables, on product_id and the creation_date, to get the complete row.


          Try the following:



          select uph.creation_date, 
          p.name,
          p.product_id
          from product p
          join user_product_history uph
          on p.product_id = uph.product_id and
          uph.user_id = 124
          join (select product_id,
          MAX(creation_date) AS max_creation_date
          from user_product_history
          where user_id = 124
          group by product_id) dt
          on dt.product_id = uph.product_id and
          dt.max_creation_date = uph.creation_date
          order by uph.creation_date desc





          share|improve this answer























          • thanks for your prompt reply and your answer is works! Abit out of topic, I will using this statement in php API. When I apply this statement and replace 124 to ?, i hit error as below:-<h1>A Database Error Occurred</h1> <p>Error Number: 1064</p><p>You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? join (select product_id, MAX(creation_date) AS max_creat' at line 7</p><p>select uph.creation_date, Any idea?
            – henry
            Nov 5 at 4:40












          • @henry please share the application code (eg: PHP) you are using to run this query.
            – Madhur Bhaiya
            Nov 5 at 4:45










          • Hi. @Madhur, edited in my post, kindly review. Thanks!
            – henry
            Nov 5 at 7:15










          • @henry note that number of ? has increased now with my query. user_id is checked twice now. You should use array($data['user_id'], $data['user_id']) instead
            – Madhur Bhaiya
            Nov 5 at 7:18






          • 1




            Opps, you are right, I forgot about it, Thanks Madhur!
            – henry
            Nov 5 at 7:29


















          up vote
          0
          down vote













          select 
          uph.creation_date,
          p.name,p.product_id
          from
          product p
          left join user_product_history uph on p.product_id = uph.product_id
          where
          uph.user_id = 124 and
          uph.creation_date = (select
          max(creation_date)
          from
          user_product_history)
          order by
          uph.creation_date desc





          share|improve this answer

















          • 1




            This will return only one row.
            – Madhur Bhaiya
            Nov 5 at 4:04










          • hi @dwir182, I would like to return more than 1 row result.
            – henry
            Nov 5 at 7:15











          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',
          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%2f53148080%2fhow-to-group-by-product-id-with-latest-creation-date-in-mysql%23new-answer', 'question_page');
          }
          );

          Post as a guest
































          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          3
          down vote



          accepted











          • Firstly, you dont need a Left Join here, as you are filtering on user_product_history table also. It does seem like you want to show only those product(s), which has a creation_date corresponding to user_id = 124. So, you can simply use Inner Join instead.

          • In a derived table (sub-select query), determine the maximum value of creation_date for every product_id.

          • Now, use this result-set to join to the main tables, on product_id and the creation_date, to get the complete row.


          Try the following:



          select uph.creation_date, 
          p.name,
          p.product_id
          from product p
          join user_product_history uph
          on p.product_id = uph.product_id and
          uph.user_id = 124
          join (select product_id,
          MAX(creation_date) AS max_creation_date
          from user_product_history
          where user_id = 124
          group by product_id) dt
          on dt.product_id = uph.product_id and
          dt.max_creation_date = uph.creation_date
          order by uph.creation_date desc





          share|improve this answer























          • thanks for your prompt reply and your answer is works! Abit out of topic, I will using this statement in php API. When I apply this statement and replace 124 to ?, i hit error as below:-<h1>A Database Error Occurred</h1> <p>Error Number: 1064</p><p>You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? join (select product_id, MAX(creation_date) AS max_creat' at line 7</p><p>select uph.creation_date, Any idea?
            – henry
            Nov 5 at 4:40












          • @henry please share the application code (eg: PHP) you are using to run this query.
            – Madhur Bhaiya
            Nov 5 at 4:45










          • Hi. @Madhur, edited in my post, kindly review. Thanks!
            – henry
            Nov 5 at 7:15










          • @henry note that number of ? has increased now with my query. user_id is checked twice now. You should use array($data['user_id'], $data['user_id']) instead
            – Madhur Bhaiya
            Nov 5 at 7:18






          • 1




            Opps, you are right, I forgot about it, Thanks Madhur!
            – henry
            Nov 5 at 7:29















          up vote
          3
          down vote



          accepted











          • Firstly, you dont need a Left Join here, as you are filtering on user_product_history table also. It does seem like you want to show only those product(s), which has a creation_date corresponding to user_id = 124. So, you can simply use Inner Join instead.

          • In a derived table (sub-select query), determine the maximum value of creation_date for every product_id.

          • Now, use this result-set to join to the main tables, on product_id and the creation_date, to get the complete row.


          Try the following:



          select uph.creation_date, 
          p.name,
          p.product_id
          from product p
          join user_product_history uph
          on p.product_id = uph.product_id and
          uph.user_id = 124
          join (select product_id,
          MAX(creation_date) AS max_creation_date
          from user_product_history
          where user_id = 124
          group by product_id) dt
          on dt.product_id = uph.product_id and
          dt.max_creation_date = uph.creation_date
          order by uph.creation_date desc





          share|improve this answer























          • thanks for your prompt reply and your answer is works! Abit out of topic, I will using this statement in php API. When I apply this statement and replace 124 to ?, i hit error as below:-<h1>A Database Error Occurred</h1> <p>Error Number: 1064</p><p>You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? join (select product_id, MAX(creation_date) AS max_creat' at line 7</p><p>select uph.creation_date, Any idea?
            – henry
            Nov 5 at 4:40












          • @henry please share the application code (eg: PHP) you are using to run this query.
            – Madhur Bhaiya
            Nov 5 at 4:45










          • Hi. @Madhur, edited in my post, kindly review. Thanks!
            – henry
            Nov 5 at 7:15










          • @henry note that number of ? has increased now with my query. user_id is checked twice now. You should use array($data['user_id'], $data['user_id']) instead
            – Madhur Bhaiya
            Nov 5 at 7:18






          • 1




            Opps, you are right, I forgot about it, Thanks Madhur!
            – henry
            Nov 5 at 7:29













          up vote
          3
          down vote



          accepted







          up vote
          3
          down vote



          accepted







          • Firstly, you dont need a Left Join here, as you are filtering on user_product_history table also. It does seem like you want to show only those product(s), which has a creation_date corresponding to user_id = 124. So, you can simply use Inner Join instead.

          • In a derived table (sub-select query), determine the maximum value of creation_date for every product_id.

          • Now, use this result-set to join to the main tables, on product_id and the creation_date, to get the complete row.


          Try the following:



          select uph.creation_date, 
          p.name,
          p.product_id
          from product p
          join user_product_history uph
          on p.product_id = uph.product_id and
          uph.user_id = 124
          join (select product_id,
          MAX(creation_date) AS max_creation_date
          from user_product_history
          where user_id = 124
          group by product_id) dt
          on dt.product_id = uph.product_id and
          dt.max_creation_date = uph.creation_date
          order by uph.creation_date desc





          share|improve this answer















          • Firstly, you dont need a Left Join here, as you are filtering on user_product_history table also. It does seem like you want to show only those product(s), which has a creation_date corresponding to user_id = 124. So, you can simply use Inner Join instead.

          • In a derived table (sub-select query), determine the maximum value of creation_date for every product_id.

          • Now, use this result-set to join to the main tables, on product_id and the creation_date, to get the complete row.


          Try the following:



          select uph.creation_date, 
          p.name,
          p.product_id
          from product p
          join user_product_history uph
          on p.product_id = uph.product_id and
          uph.user_id = 124
          join (select product_id,
          MAX(creation_date) AS max_creation_date
          from user_product_history
          where user_id = 124
          group by product_id) dt
          on dt.product_id = uph.product_id and
          dt.max_creation_date = uph.creation_date
          order by uph.creation_date desc






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 5 at 4:22

























          answered Nov 5 at 4:09









          Madhur Bhaiya

          13.8k52035




          13.8k52035












          • thanks for your prompt reply and your answer is works! Abit out of topic, I will using this statement in php API. When I apply this statement and replace 124 to ?, i hit error as below:-<h1>A Database Error Occurred</h1> <p>Error Number: 1064</p><p>You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? join (select product_id, MAX(creation_date) AS max_creat' at line 7</p><p>select uph.creation_date, Any idea?
            – henry
            Nov 5 at 4:40












          • @henry please share the application code (eg: PHP) you are using to run this query.
            – Madhur Bhaiya
            Nov 5 at 4:45










          • Hi. @Madhur, edited in my post, kindly review. Thanks!
            – henry
            Nov 5 at 7:15










          • @henry note that number of ? has increased now with my query. user_id is checked twice now. You should use array($data['user_id'], $data['user_id']) instead
            – Madhur Bhaiya
            Nov 5 at 7:18






          • 1




            Opps, you are right, I forgot about it, Thanks Madhur!
            – henry
            Nov 5 at 7:29


















          • thanks for your prompt reply and your answer is works! Abit out of topic, I will using this statement in php API. When I apply this statement and replace 124 to ?, i hit error as below:-<h1>A Database Error Occurred</h1> <p>Error Number: 1064</p><p>You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? join (select product_id, MAX(creation_date) AS max_creat' at line 7</p><p>select uph.creation_date, Any idea?
            – henry
            Nov 5 at 4:40












          • @henry please share the application code (eg: PHP) you are using to run this query.
            – Madhur Bhaiya
            Nov 5 at 4:45










          • Hi. @Madhur, edited in my post, kindly review. Thanks!
            – henry
            Nov 5 at 7:15










          • @henry note that number of ? has increased now with my query. user_id is checked twice now. You should use array($data['user_id'], $data['user_id']) instead
            – Madhur Bhaiya
            Nov 5 at 7:18






          • 1




            Opps, you are right, I forgot about it, Thanks Madhur!
            – henry
            Nov 5 at 7:29
















          thanks for your prompt reply and your answer is works! Abit out of topic, I will using this statement in php API. When I apply this statement and replace 124 to ?, i hit error as below:-<h1>A Database Error Occurred</h1> <p>Error Number: 1064</p><p>You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? join (select product_id, MAX(creation_date) AS max_creat' at line 7</p><p>select uph.creation_date, Any idea?
          – henry
          Nov 5 at 4:40






          thanks for your prompt reply and your answer is works! Abit out of topic, I will using this statement in php API. When I apply this statement and replace 124 to ?, i hit error as below:-<h1>A Database Error Occurred</h1> <p>Error Number: 1064</p><p>You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? join (select product_id, MAX(creation_date) AS max_creat' at line 7</p><p>select uph.creation_date, Any idea?
          – henry
          Nov 5 at 4:40














          @henry please share the application code (eg: PHP) you are using to run this query.
          – Madhur Bhaiya
          Nov 5 at 4:45




          @henry please share the application code (eg: PHP) you are using to run this query.
          – Madhur Bhaiya
          Nov 5 at 4:45












          Hi. @Madhur, edited in my post, kindly review. Thanks!
          – henry
          Nov 5 at 7:15




          Hi. @Madhur, edited in my post, kindly review. Thanks!
          – henry
          Nov 5 at 7:15












          @henry note that number of ? has increased now with my query. user_id is checked twice now. You should use array($data['user_id'], $data['user_id']) instead
          – Madhur Bhaiya
          Nov 5 at 7:18




          @henry note that number of ? has increased now with my query. user_id is checked twice now. You should use array($data['user_id'], $data['user_id']) instead
          – Madhur Bhaiya
          Nov 5 at 7:18




          1




          1




          Opps, you are right, I forgot about it, Thanks Madhur!
          – henry
          Nov 5 at 7:29




          Opps, you are right, I forgot about it, Thanks Madhur!
          – henry
          Nov 5 at 7:29












          up vote
          0
          down vote













          select 
          uph.creation_date,
          p.name,p.product_id
          from
          product p
          left join user_product_history uph on p.product_id = uph.product_id
          where
          uph.user_id = 124 and
          uph.creation_date = (select
          max(creation_date)
          from
          user_product_history)
          order by
          uph.creation_date desc





          share|improve this answer

















          • 1




            This will return only one row.
            – Madhur Bhaiya
            Nov 5 at 4:04










          • hi @dwir182, I would like to return more than 1 row result.
            – henry
            Nov 5 at 7:15















          up vote
          0
          down vote













          select 
          uph.creation_date,
          p.name,p.product_id
          from
          product p
          left join user_product_history uph on p.product_id = uph.product_id
          where
          uph.user_id = 124 and
          uph.creation_date = (select
          max(creation_date)
          from
          user_product_history)
          order by
          uph.creation_date desc





          share|improve this answer

















          • 1




            This will return only one row.
            – Madhur Bhaiya
            Nov 5 at 4:04










          • hi @dwir182, I would like to return more than 1 row result.
            – henry
            Nov 5 at 7:15













          up vote
          0
          down vote










          up vote
          0
          down vote









          select 
          uph.creation_date,
          p.name,p.product_id
          from
          product p
          left join user_product_history uph on p.product_id = uph.product_id
          where
          uph.user_id = 124 and
          uph.creation_date = (select
          max(creation_date)
          from
          user_product_history)
          order by
          uph.creation_date desc





          share|improve this answer












          select 
          uph.creation_date,
          p.name,p.product_id
          from
          product p
          left join user_product_history uph on p.product_id = uph.product_id
          where
          uph.user_id = 124 and
          uph.creation_date = (select
          max(creation_date)
          from
          user_product_history)
          order by
          uph.creation_date desc






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 5 at 4:02









          dwir182

          1,482318




          1,482318








          • 1




            This will return only one row.
            – Madhur Bhaiya
            Nov 5 at 4:04










          • hi @dwir182, I would like to return more than 1 row result.
            – henry
            Nov 5 at 7:15














          • 1




            This will return only one row.
            – Madhur Bhaiya
            Nov 5 at 4:04










          • hi @dwir182, I would like to return more than 1 row result.
            – henry
            Nov 5 at 7:15








          1




          1




          This will return only one row.
          – Madhur Bhaiya
          Nov 5 at 4:04




          This will return only one row.
          – Madhur Bhaiya
          Nov 5 at 4:04












          hi @dwir182, I would like to return more than 1 row result.
          – henry
          Nov 5 at 7:15




          hi @dwir182, I would like to return more than 1 row result.
          – henry
          Nov 5 at 7:15


















           

          draft saved


          draft discarded



















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53148080%2fhow-to-group-by-product-id-with-latest-creation-date-in-mysql%23new-answer', 'question_page');
          }
          );

          Post as a guest




















































































          這個網誌中的熱門文章

          Tangent Lines Diagram Along Smooth Curve

          Yusuf al-Mu'taman ibn Hud

          Zucchini