mysql - 如何避免在下面的 mysql 查询中出现重复行的情况?

标签 mysql sql

这是我的表(多对多关系)。 他们的目标 - 保留不同请求的状态更改历史记录。 (我从插图中删除了对问题没有意义的所有字段)

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/

相关文章:

php - 将一张表中的两列合并为一个输出

mysql - 使用 MySQL 返回列中的第一个唯一值一次

sql - 返回具有完全相同员工的所有组

SQL Server - 正确分解付款

mysql - Mysql单查询统计多表数据

mysql - 如何用新的ID替换重复的ID?

mysql按多数票排序

sql - 需要帮助在 Postgres 中用窗口函数替换子查询

mysql - 一行中一对多所有详细信息的 SELECT 语句

MySQL:通过感知哈希相似性对结果进行分组