2013-07-02 63 views
1

我有這兩個表:MySQL的順序由其它表的行

表一:
--- ID --- Name ---
表B:
--- ID --- ID_of_a --- Date ---

現在我要訂購的table a由行Date(降序)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" }
從表ID的將是正確的順序:1 --- 2
查詢:

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


但是,這並不有時工作。

+0

什麼東西不能在上班時間跑? –

+0

你用什麼查詢「有時候不行」 – RedBaron

+0

哦,對不起。我總是忘了這一點。 - 編輯 –

回答

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 
+0

工作,謝謝! –

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

我認爲它可以被重新寫入更有效地