我有两个表,tickets
和ticket_updates
ticket_updates
tickets
都有多行
如何在tickets
datetime
选择ticket_updates
排序
我想从最早的datetime
(DESC)ticket_updates
datetime
订购
我认为以下内容可能有效,但是在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 :(得分: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)
上的索引。
答案 1 :(得分:0)
我认为你想要这样的东西,这几乎就是你在编辑后发布的东西。如果运行速度太慢,则可能需要为查询运行EXPLAIN并添加适当的索引。要么是日期时间,要么是戈登建议的票号/日期时间的复合键。
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