Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8209121
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T09:36:47+00:00 2026-06-07T09:36:47+00:00

I have two tables in MySQL sales database: Orders table: CREATE TABLE salestest.`orders` (

  • 0

I have two tables in MySQL sales database:

Orders table:

CREATE TABLE salestest.`orders` (  
`ID` int(11) unsigned NOT NULL auto_increment,  
`OrderDate` datetime NOT NULL,  
`CustomerID` int(11) unsigned NOT NULL,  
PRIMARY KEY (`ID`),  
UNIQUE KEY `ID` (`ID`),  
KEY `OrderDate` (`OrderDate`),  
KEY `CustomerID` (`CustomerID`)  
) ENGINE=InnoDB;  

INSERT INTO salestest.orders VALUES  
( 1, '2012-04-15', 1 ),  
( 2, '2012-05-20', 1 ),  
( 3, '2012-06-30', 1 );  

OrderDetails table:

CREATE TABLE salestest.`OrderDetails` (  
`ID` int(11) unsigned NOT NULL auto_increment,  
`OrderID` int(11) unsigned NOT NULL,  
`ProductID` int(11) unsigned NOT NULL,  
`Price` double NOT NULL default '0',  
PRIMARY KEY  (`ID`),  
UNIQUE KEY `ID` (`ID`),  
KEY `OrderID` (`OrderID`),  
KEY `ProductID` (`ProductID`),  
CONSTRAINT `OrderID_fk` FOREIGN KEY (`OrderID`) REFERENCES `orders` (`ID`)  
) ENGINE=InnoDB;  

INSERT INTO salestest.OrderDetails VALUES  
( 1, 1, 1, 2 ),  
( 2, 1, 2, 15 ),  
( 3, 1, 3, 22 ),  
( 4, 2, 1, 3 ),  
( 5, 2, 2, 17 ),  
( 6, 2, 3, 23 ),  
( 7, 2, 4, 40 ),  
( 8, 3, 1, 4 ),  
( 9, 3, 2, 20 );  

Now I need to select for each customer, the last price they purchase each product.

The easy way to do it is by using a subquery:

SELECT od2.CustomerID,od2.ProductID, od2.Price AS LastPrice, od2.OrderDate AS LastDate  
FROM (SELECT o1.ID, o1.CustomerID, o1.OrderDate, od1.ProductID, od1.Price  
  FROM orders AS o1  
  LEFT JOIN OrderDetails as od1 ON o1.ID=od1.OrderID  
  ORDER BY OrderDate DESC) AS od2  
GROUP BY CustomerID, ProductID  
ORDER BY CustomerID, ProductID;  

Result:

CustomerID ProductID LastPrice LastDate
1 1 4 2012-06-30 00:00:00
1 2 20 2012-06-30 00:00:00
1 3 23 2012-05-20 00:00:00
1 4 40 2012-05-20 00:00:00

Now the question; how is it possible to get the same result if I want to avoid sub-query, temp tables or a view, I only want to use joins; this query is a small part of a much larger query, and having sub-query is highly inefficient.

I tried this query:

SELECT o1.CustomerID,od1.ProductID, od1.Price AS LastPrice, o1.OrderDate AS LastDate
FROM Orders AS o1 LEFT JOIN OrderDetails as od1 ON o1.ID=od1.OrderID
GROUP BY CustomerID, ProductID
ORDER BY CustomerID, ProductID;

but it gives a different result:

CustomerID ProductID LastPrice LastDate
1 1 2 2012-04-15 00:00:00
1 2 15 2012-04-15 00:00:00
1 3 22 2012-04-15 00:00:00
1 4 40 2012-05-20 00:00:00

As you see, LastPrice & LastDate are not correct. I also tried Allen’s suggestion, but the result is:

CustomerID ProductID LastPrice LastDate
1 1 4 2012-06-30 00:00:00
1 2 20 2012-06-30 00:00:00

first query from spencer’s answer results duplicated products:

CustomerID ProductID LastPrice LastDate
1 3 22 2012-04-15 00:00:00
1 3 23 2012-05-20 00:00:00
1 4 40 2012-05-20 00:00:00
1 1 4 2012-06-30 00:00:00
1 2 20 2012-06-30 00:00:00

other answers all use sub-query, which I am trying to avoid.
any suggestions?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T09:36:49+00:00Added an answer on June 7, 2026 at 9:36 am

    UPDATE:

    I have been unable to reproduce the result set using only joins (without using an inline view or a correlated subquery).

    I don’t think it’s possible to reliably return the specified result set wihtout using an inline view or a correlated subquery.


    This returns the specified result, but with no inlineview and no subqueries. (But that’s not to say that this is going to be the “fastest” query that returns the result set.

    NOT WORKING… please standby

    SELECT o1.CustomerID, d1.ProductID, d1.Price, o1.Orderdate
      FROM orders o1
      JOIN OrderDetails d1 ON d1.OrderID = o1.ID
      LEFT      
      JOIN orders o2 
        ON o1.CustomerID = o2.CustomerID
           AND o1.ID <> o2.ID
           AND (o1.OrderDate < o2.OrderDate
               OR (o1.OrderDate = o2.OrderDate AND o1.ID < o2.ID)
               )
      LEFT
      JOIN OrderDetails d2
        ON d2.OrderID = o2.ID
           AND d2.ProductID = d1.ProductId
           AND (o1.OrderDate < o2.OrderDate
               OR (o1.OrderDate = o2.OrderDate AND o1.ID < o2.ID)
               OR (o1.OrderDate = o2.OrderDate AND o1.ID = o2.ID AND d1.ID < d2.ID )
               )
     WHERE d2.ID IS NULL 
    

    This query joins the tables to themselves and filters out the “topmost” row for each group.

    —

    Conceptually, that query is the same as the following query. The following query makes use of an “inline view” (aliased as a and b). The purpose of the inline view is really just to get CustomerID and OrderDate associated with each OrderDetail line.

     SELECT a.CustomerID, a.ProductID, a.Price, a.Orderdate
       FROM (SELECT o1.CustomerID, d1.ProductID, d1.Price, o1.OrderDate, d1.OrderID, d1.ID
               FROM orders o1
               JOIN OrderDetails d1 ON d1.OrderID = o1.ID
            ) a
       LEFT      
       JOIN (SELECT o2.CustomerID, d2.ProductID, d2.Price, o2.OrderDate, d2.OrderID, d2.ID
               FROM orders o2
               JOIN OrderDetails d2 ON d2.OrderID = o2.ID
            ) b
         ON a.CustomerID = b.CustomerID
            AND a.ProductID = b.ProductId
            AND a.OrderID <> b.OrderID
            AND a.ID <> b.ID
            AND (a.OrderDate < b.OrderDate 
                 OR (a.OrderDate = b.OrderDate AND a.OrderID < b.OrderID)
                 OR (a.OrderDate = b.OrderDate AND a.OrderID = b.OrderID AND a.ID < b.ID))
      WHERE b.ID IS NULL 
    

    We’d use a common table expression (CTE) in place of the inline views, if MySQL supported them.


    Finally, here’s an entirely different approach, which uses MySQL “user variables” to simulate the analytic functions that are missing from MySQL.

    SELECT q.CustomerID
         , q.ProductID
         , q.Price
         , q.OrderDate
      FROM (SELECT IF(p.CustomerID = @last_customerid,IF(p.ProductID = @last_productid,0,1),1) AS break
                 , @last_customerid := p.CustomerID AS CustomerID
                 , @last_productid := p.ProductID AS ProductID
                 , p.Price
                 , p.OrderDate
             FROM (SELECT @last_customerid := NULL, @last_productid := NULL) i
             JOIN ( SELECT o.CustomerID, d.ProductID, o.OrderDate, d.Price 
                      FROM orders o
                      JOIN OrderDetails d ON d.OrderID = o.ID
                     ORDER BY o.CustomerID, d.ProductID, o.OrderDate DESC
                  ) p
           ) q
      WHERE q.break = 1
    

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have two tables in a Mysql database. PACKAGES: ID (auto_increment) CATEGORY (INT) NAME
I have two mysql tables - a sales table: +----------------+------------------------------+------+-----+---------+-------+ | Field | Type
I have two MySql tables like the following: Cat ------ id : INT NOT
I have two mysql tables: Item containing items that one can buy: CREATE TABLE
I have two MySQL tables, j and t, with a third normalising table, jt.
I have two tables in my MySQL database, one is a library of all
I have two MySQL tables a and b with fields x and y. Table
I have two mySQL tables as follows: [product] table P_id | Name | Quantity
I have two tables on mysql: users, and management. The users table has a
I have two tables in MySql database, one is sales_order and the other is

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.