根据另一表列以DESC顺序对MySQL查询结果进行排序

时间:2018-08-25 03:25:01

标签: mysql sql sql-order-by

你好!

我的数据库中有两个表

表(订单

+--------+----+---------+
|  name  | id | user_id |
+--------+----+---------+
| order1 | 1  | 3       |
| order2 | 2  | 5       |
| order3 | 3  | 5       |
| order4 | 4  | 1       |
| order5 | 5  | 5       |
+--------+----+---------+

表( reported_orders

+----------+---------+------------+
| order_id | user_id | time       |
+----------+---------+------------+
| 2        | 5       | 1535110516 |
+----------+---------+------------+
| 3        | 5       | 1535166516 |
+----------+---------+------------+
| 5        | 5       | 1535168651 |
+----------+---------+------------+

我执行此查询时

SELECT name,id FROM orders 
WHERE 
user_id=5
AND 
id IN (SELECT order_id FROM reported_orders WHERE user_id=5 ORDER BY time DESC )
LIMIT 0, 12

我得到结果

+--------+----+
|  name  | id |
+--------+----+
| order2 | 2  |
+--------+----+
| order3 | 3  |
+--------+----+
| order5 | 5  |
+--------+----+

但我想得到类似的结果

+--------+----+
|  name  | id |
+--------+----+
| order5 | 5  |
+--------+----+
| order3 | 3  |
+--------+----+
| order2 | 2  |
+--------+----+

我在查询中使用ORDER BY time DESC来根据time表中的reported_orders以降序获取结果,但这不起作用

3 个答案:

答案 0 :(得分:1)

此查询与我合作。

SELECT orders.name,orders.id, reported_orders.time
FROM orders
INNER JOIN reported_orders
ON (orders.id=reported_orders.order_id) 
WHERE 
(orders.user_id=5 AND reported_orders.user_id=5) 
ORDER BY time DESC

答案 1 :(得分:0)

尝试此查询

SELECT a.name,a.id FROM orders a join reported_orders b on a.id=b.id where a.user_id=5 and b.user_id=5 order by a.id desc

答案 2 :(得分:0)

这对我有用。

select o.name, o.id from orders o natural join reported_orders ro order by ro.time desc;