2014-11-21 92 views
0

由一個行排序我有兩個表,ticketsticket_updates兩個表中從第二個表

有在ticket_updates多行按每一行在tickets

如何從tickets排序方式選擇選擇datetimeticket_updates

我想通過datetimeticket_updates從最早datetime(DESC)

訂貨

我認爲以下可能會工作,但時間過久,以在phpMyAdmin運行,我得到一個內部服務器錯誤:

SELECT t.ticketnumber, t.subject, t.contact_name FROM tickets t JOIN ticket_updates tu on t.ticketnumber = tu.ticketnumber group by tu.ticketnumber order by tu.datetime DESC 
+0

研究'JOIN' – 2014-11-21 23:05:13

+0

檢查更新:) – user3815283 2014-11-21 23:06:22

回答

2

你可以做這樣的事情:

select t.* 
from tickets t 
order by (select min(datetime) from ticket_updates tu where tu.ticketid = t.ticketid); 

編輯:

您也可以嘗試用group by

select t.* 
from tickets t join 
    (select ticketid, min(datetime) as mindt 
     from ticket_updates tu 
     group by ticketid 
    ) tu 
    on tu.ticketid = t.ticketid 
group by tu.mindt desc; 

或者,原始查詢可以利用ticket_updates(ticketid, datetime)上的索引。

+0

這需要花費一些時間來運行查詢 – user3815283 2014-11-22 21:58:27

0

我想你會想要這樣的東西,這幾乎是你編輯後張貼的東西。如果運行速度太慢,則可能需要運行查詢的EXPLAIN並添加適當的索引。無論是日期時間,還是戈登建議的複合密鑰,都可以用作ticketnumber/datetime。

SELECT t.ticketnumber, t.subject, t.contact_name FROM ticket_updates tu 
INNER JOIN tickets t ON t.ticketnumber = tu.ticketnumber 
GROUP BY tu.ticketnumber 
ORDER BY tu.datetime DESC 

SELECT t.ticketnumber, t.subject, t.contact_name FROM ticket_updates tu 
INNER JOIN tickets t using(ticketnumber) 
GROUP BY tu.ticketnumber 
ORDER BY tu.datetime DESC 
相關問題