I have two tables, tickets
and ticket_updates
There are multiple rows in ticket_updates
for each one row in tickets
how can i select from tickets
ordering by datetime
in ticket_updates
i want to order by datetime
in ticket_updates
from the earliest datetime
(DESC)
i thought the following may work, however it takes too long to run in PHPMyAdmin and i get an internal server error:
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
:
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)
.
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. 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.