简体   繁体   中英

Mysql sort the results based on 2 columns from different tables

I have 2 tables with the following structure

Products

id | name      | created_at          |
 1 | Produt1   | 2019-11-01 19:05:56 |
 2 | Product 2 | 2020-01-28 19:05:56 |
 3 | Product 3 | 2020-01-26 19:05:56 |

Draws

id | product_id |draw_number | created_at          |
 1 |          1 |          1 | 2020-01-28 19:05:56 | 
 2 |          1 |          2 | 2020-01-27 19:05:56 |

The scenario is, we have 3 products in product table and for product 1, we have 2 entries in draws table.

I am looking for a query here that selects the data from products table and data should be ordered by

  1. If draws created_at exists, then order by draw created at
  2. If no draws, sort by created at of products table.

Result output should be like this

id | name      | created_at          |
 1 | Produt1   | 2019-01-28 19:05:56 | //created_at of draws of latest draw for this product
 2 | Product 2 | 2020-01-28 19:05:56 |
 3 | Product 3 | 2020-01-26 19:05:56 |

How can I selected the expected data? TIA

Test

SELECT t1.*
FROM Products t1
LEFT JOIN ( SELECT t2.product_id,
                   MAX(t2.created_at) created_at 
            FROM Draws t2
            GROUP BY product_id ) t3 ON t1.id = t3.product_id
ORDER BY GREATEST(t1.created_at, t3.created_at) DESC

This give you the wanted result

CREATE TABLE Draws (`id` int, `product_id` int, `draw_number` int, `created_at` datetime) ; INSERT INTO Draws (`id`, `product_id`, `draw_number`, `created_at`) VALUES (1, 1, 1, '2020-01-28 19:05:56'), (2, 1, 2, '2020-01-27 19:05:56') ;
\n \n\n \n
CREATE TABLE Products (`id` int, `name` varchar(9), `created_at` datetime) ; INSERT INTO Products (`id`, `name`, `created_at`) VALUES (1, 'Produt1', '2019-11-01 19:05:56'), (2, 'Product 2', '2020-01-28 19:05:56'), (3, 'Product 3', '2020-01-26 19:05:56') ;
\n \n\n \n
SELECT p.id,p.name,MAX( IFNULL(d.`created_at` , p.`created_at`)) FROM Draws d RIGHT JOIN Products p ON d.product_id = p.id GROUP BY p.id,p.name ORDER BY p.id;
\nid | name | MAX( IFNULL(d.`created_at` , p.`created_at`)) \n-: |  :-------- |  :-------------------------------------------- \n 1 |  Produt1 | 2020-01-28 19:05:56                           \n 2 |  Product 2 | 2020-01-28 19:05:56                           \n 3 |  Product 3 | 2020-01-26 19:05:56                           \n

db<>fiddle here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM