这是我的表(多对多关系)。 他们的目标 - 保留不同请求的状态更改历史记录。 (我从插图中删除了对问题没有意义的所有字段)
1.请求
id (primary, ai) | name (varchar) | phone (varchar) | text (varchar)
1 | Maria | 9232342323 | "fist text"
2 | Petr | 2342342323 | "second text"
3 | Lenny | 2342342323 | "third text"
2.状态
id (primary, ai) | title (varchar)
1 | New
2 | In progress
3 | Abort
3.Requests_has_Statuses
id (primary, ai) | requests_id (fk) | statuses_id (fk) | comment (varchar) | date (timestamp)
1 | 1 | 1 | "Fist comment about a Maria's request" | 2014-08-08 12:24
2 | 1 | 2 | "Second comment about Maria" | 2014-08-08 12:26
3 | 1 | 2 | "Third comment about Maria" | 2014-08-08 12: 57
4 | 2 | 1 | "First comment about Petr" | 2014-08-08 13:23
5 | 3 | 1 | "First comment about Lenny" | 2014-08-08 13:45
6 | 2 | 3 | "Second comment about Petr" | 2014-08-08 14:00
我的目标是选择这样的输出:
1 | Maria | 9232342323 | "In progress" | "Third comment about Maria" | 2014-08-08 12: 57
2 | Petr | 2342342323 | "Abort" | "Second comment about Petr" | 2014-08-08 14:00
3 | Lenny | 2342342323 | "New" | "First comment about Lenny" | 2014-08-08 13:45
简单来说,我需要输出每个请求的当前实际状态和信息。
我试着这样做:
SELECT r.name, r.phone, st.title, rhs.comment, rhs.date
FROM requests AS r
INNER JOIN Requests_has_Statuses AS rhs ON rhs.requests_id = r.id
INNER JOIN Statuses AS st ON rhs.statuses_id = st.id;
但是我得到了一个不必要的重复,比如:
1 | Maria | 9232342323 | "New" | "Fist comment about a Maria's request" | 2014-08-08 12:24
1 | Maria | 9232342323 | "In progress" | "Second comment about Maria" | 2014-08-08 12: 26
1 | Maria | 9232342323 | "In progress" | "Third comment about Maria" | 2014-08-08 12: 57
2 | Petr | 2342342323 | "New" | "First comment about Petr" |2014-08-08 13:23
3 | Lenny | 2342342323 | "New" | "First comment about Lenny" | 2014-08-08 13:45
2 | Petr | 2342342323 | "Abort" | "Second comment about Petr" | 2014-08-08 14:00
您能帮我提供建议或解决方案吗? 谢谢
最佳答案
试试这个:
SELECT r.id, r.phone, st.title, rhs.comment, rhs.date
FROM (
SELECT r.id, max(rhs.date) AS date
FROM Requests_has_Statuses AS rhs
INNER JOIN Requests r ON r.id = rhs.requestId
GROUP BY r.id) AS temp
INNER JOIN Requests AS r ON temp.id = r.id
INNER JOIN Requests_has_Statuses AS rhs ON rhs.requestId = temp.id and rhs.date = temp.date
INNER JOIN Statuses AS st ON rhs.statusId = st.id
关于mysql - 如何避免在下面的 mysql 查询中出现重复行的情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25208311/