Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL按其他表排序行_Mysql_Date - Fatal编程技术网

MySQL按其他表排序行

MySQL按其他表排序行,mysql,date,Mysql,Date,我有那两张桌子: 表a: --ID--Name-- 表b: --ID--ID--a的日期-- 现在我想按表b的日期(desc)按最新日期对表a的行进行排序。 例子: 表a包含ID为“1”和“2”的行。 表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.

我有那两张桌子:

表a:
--ID--Name--

表b:
--ID--ID--a的日期--

现在我想按
表b
日期(desc)按最新日期对
表a
的行进行排序。 例子:
表a
包含ID为“1”和“2”的行。
表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


但这有时不起作用

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

select a.*
from a left outer join
     b
     on a.id = b.id
order by b.date desc
如果每个
a
b
中有多行,则需要一个
分组依据

select a.*
from a left outer join
     b
     on a.id = b.id
group by a.id
order by max(b.date) desc
怎么样

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)
基本上,您首先为a的每个
id\u选择最长日期,然后将其加入到
a


我认为可以重新编写,以更高效地运行

什么有时不起作用?您使用什么查询“有时不起作用”哦,对不起。我完全忘记了Edited不应期望顺序为
2--1
,因为2具有最新的日期,您需要降序排序