MySQL按其他表排序

时间:2013-07-02 15:12:23

标签: mysql date

我有两张桌子:

表a:
--- ID --- Name ---
表b:
--- ID --- ID_of_a --- Date ---

现在,我想按table a Date的最新日期table b(desc)排序Table a行。 例: Table b包含ID为“1”和“2”的行 SELECT DISTINCT a.ID, a.Name FROM a, b WHERE a.ID=b.ID_of_a ORDER BY b.Date desc 包含以下行:{ID,ID_of_a,Date} {1,1,“2013-06-30”},{2,1,“2013-07-01”},{3,2, “2013-07-02”} 表a中正确的ID顺序为:1 --- 2
查询:

{{1}}


但这有时不起作用。

2 个答案:

答案 0 :(得分:2)

假设表之间存在1-1关系:

select a.*
from a left outer join
     b
     on a.id = b.id
order by b.date desc

如果每个b的{​​{1}}中有多行,那么您需要a

group by

答案 1 :(得分:0)

怎么样

select a.name,a.id from a join (select id_of_a as id_a,max(dt) as max_dt from b group by id_of_a order by max_dt desc) e on e.id_a=a.id

实施例

mysql> select * from a;
+----+------+
| id | name |
+----+------+
|  1 | a    |
|  2 | b    |
+----+------+
2 rows in set (0.00 sec)

mysql> select * from b;
+----+---------+------------+
| id | id_of_a | dt         |
+----+---------+------------+
|  1 |       1 | 2013-06-20 |
|  2 |       2 | 2013-07-01 |
|  3 |       1 | 2013-07-02 |
+----+---------+------------+
3 rows in set (0.00 sec)

mysql> select a.name,a.id from a join (select id_of_a as id_a,max(dt) as max_dt from b group by id_of_a order by max_dt desc) e on e.id_a=a.id;
+------+----+
| name | id |
+------+----+
| a    |  1 |
| b    |  2 |
+------+----+
2 rows in set (0.00 sec)

基本上,您首先选择每个id_of_a的最长日期,然后将其加入a

我认为可以重写它以更有效地运行