1

我有这两张桌子:

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

现在我想按最新日期table aDate(desc) 对行进行排序。table b示例: Table a具有 ID 为“1”和“2”的行。
Table b有这样的行:{ID, ID_of_a, Date} {1, 1, "2013-06-30"}, {2, 1, "2013-07-01" }, {3, 2, "2013-07- 02" }
表 a 中 ID 的正确顺序是:1 --- 2
查询:

SELECT DISTINCT a.ID, a.Name FROM a, b WHERE a.ID=b.ID_of_a ORDER BY b.Date desc


但这有时行不通。

4

2 回答 2

2

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

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

b如果每个中有多行a,那么您需要一个group by

select a.*
from a left outer join
     b
     on a.id = b.id
group by a.id
order by max(b.date) desc
于 2013-07-02T15:14:57.260 回答
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

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

于 2013-07-02T15:36:31.103 回答