[英]select from two tables ordering by one row from second table
I have two tables, tickets
and ticket_updates
我有两个表, tickets
和ticket_updates
There are multiple rows in ticket_updates
for each one row in tickets
有在多行ticket_updates
在每一个行tickets
how can i select from tickets
ordering by datetime
in ticket_updates
如何在ticket_updates
按datetime
时间从订购tickets
中ticket_updates
i want to order by datetime
in ticket_updates
from the earliest datetime
(DESC) 我想从最早的datetime
(DESC)在ticket_updates
按datetime
时间进行订购
i thought the following may work, however it takes too long to run in PHPMyAdmin and i get an internal server error: 我以为以下方法可能有效,但是在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
You could do something like this: 您可以执行以下操作:
select t.*
from tickets t
order by (select min(datetime) from ticket_updates tu where tu.ticketid = t.ticketid);
EDIT: 编辑:
You can also try with a group by
: 您也可以尝试以下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;
Or, the original query can take advantage of an index on ticket_updates(ticketid, datetime)
. 或者,原始查询可以利用ticket_updates(ticketid, datetime)
上的索引。
I'd think you'd want something like this, which is pretty much what you'd posted after the edit. 我认为您想要这样的东西,这几乎是您编辑后发布的内容。 If it is running too slow you might need to run an EXPLAIN for the query and add an appropriate index. 如果运行太慢,则可能需要对查询运行EXPLAIN并添加适当的索引。 Either to datetime or potentially a compound key to ticketnumber/datetime as Gordon suggested. 就像戈登建议的那样,要么是日期时间,要么是票号/日期时间的复合键。
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
or 要么
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.