我有以下 SQL 查询,它查询我的票、ticketThreads、用户和 threadStatus 表:
SELECT tickets.threadId, ticketThreads.threadSubject, tickets.ticketCreatedDate, ticketThreads.threadCreatedDate, threadStatus.threadStatus, users.name
FROM
tickets
INNER JOIN
ticketThreads
ON
tickets.threadId = ticketThreads.threadId
INNER JOIN
threadStatus
ON
ticketThreads.threadStatus = threadStatus.id
INNER JOIN
users
ON
users.id = ticketThreads.threadUserId
WHERE
tickets.ticketId = ticketThreads.lastMessage
AND
ticketThreads.threadStatus != 3
ORDER BY
tickets.ticketCreatedDate
DESC
这返回的精简版是:
threadId |
----------
1 |
2 |
这工作正常,是我所期望的,但是为了稍微清理代码和数据库,我需要删除 ticketThreads.lastMessage 列。
如果我删除该行WHERE tickets.ticketId = ticketThreads.lastMessage
,那么这是返回内容的精简版本:
threadId |
----------
1 |
2 |
1 |
然后我需要做的是编辑上面的查询,使我能够为门票数据库中的每个 threadId 值选择最高的唯一值。
我知道MAX()
但GROUP BY
不知道如何将它们放入我上面的查询中。
表格的相关部分如下所示:
门票
ticketId | ticketUserId | threadId
-------------------------------
1 | 1 | 1
2 | 1 | 2
3 | 1 | 1
票线程
threadId | lastMessage | threadStatus
-------------------------------
1 | 3 | 4
2 | 2 | 1
我希望以上所有内容都清楚且有意义