SQL Query使用order子句从两个单独的表中进行选择

时间:2014-05-16 14:04:06

标签: mysql sql

我有两张桌子:

tickets
ticket_updates

我正在尝试运行查询,其中显示来自故障单表的数据,order by显示datetime表中的最新ticket_updates

SELECT * from tickets where status = 'Completed' order by ??? DESC LIMIT 0,50 
ticketnumber表格中的

ticketsticketnumber表格中的ticket_updates匹配

3 个答案:

答案 0 :(得分:1)

SELECT t.*
FROM tickets AS t
JOIN ticket_updates AS tu ON t.ticketnumber = tu.ticketnumber
WHERE status = 'Completed'
ORDER BY tu.datetime DESC LIMIT 50

试试这个。

答案 1 :(得分:0)

一种方法是总结ticket_updates表以获得您想要的内容:

select t.*
from tickets t join
     (select ticketid, max(datetime) as max_datetime
      from ticket_updates
      group by ticketid
     ) tu
     on t.ticketid = tu.max_datetime
order by tu.max_datetime desc
limit 0, 50;

答案 2 :(得分:0)

加入两个表,然后按:

排序
SELECT a.*
from tickets a, ticket_updates b
where a.ticketnumber = b.ticketnumber and
a.status = 'Completed'
order by b.YOUR_DATETIME_FIELD DESC LIMIT 0,50