这是我当前的mysql查询。
SELECT t.id, t.customer, t.indicator_tag, t.indicator_manu, t.indicator_model, t.created_at, t.updated_at,
( SELECT status FROM events WHERE ticket_id = t.id ORDER BY created_at DESC LIMIT 1) AS status,
( SELECT CONCAT(firstName, ' ', lastName) FROM users WHERE id = t.created_by ) AS created_by,
( SELECT CONCAT(firstName, ' ', lastName) FROM users WHERE id = t.updated_by ) AS updated_by
FROM tickets t
WHERE status = 'Pending' OR status = 'Diagnosed' OR status = 'Repaired'
ORDER BY t.customer ASC, status ASC, t.indicator_tag ASC;
上述语句中的WHERE子句不会抛出任何错误,但它也不会过滤任何错误。我仍然是SQL的新手,所以我还没有深入研究JOINS。我还应该注意,事件表将为每个票证提供多个事件,第2行的子查询将只获取最新的事件。有没有办法根据另一个表中的数据过滤结果,但只抓取每张票的最新事件?
换句话说:
TABLE票有很多事件
事件属于票据
上面的例子将显示我得到的输出。请注意,它仅显示最新状态,而不是单个故障单页面上的所有事件。如果我能提供更多信息,我很乐意帮忙。
答案 0 :(得分:1)
使用HAVING
:
SELECT t.id, t.customer, t.indicator_tag, t.indicator_manu, t.indicator_model, t.created_at, t.updated_at,
( SELECT status FROM events WHERE ticket_id = t.id ORDER BY created_at DESC LIMIT 1) AS status,
( SELECT CONCAT(firstName, ' ', lastName) FROM users WHERE id = t.created_by ) AS created_by,
( SELECT CONCAT(firstName, ' ', lastName) FROM users WHERE id = t.updated_by ) AS updated_by
FROM tickets t
HAVING status = 'Pending' OR status = 'Diagnosed' OR status = 'Repaired'
ORDER BY t.customer ASC, status ASC, t.indicator_tag ASC;
http://www.w3schools.com/sql/sql_having.asp
来自docs:
HAVING子句可以引用SELECT列表或外部子查询中select_expr中命名的任何列或别名。