如何在不使用distinct的情况下避免一对多关联中的重复记录?

时间:2016-12-23 06:43:19

标签: mysql sql postgresql

我有两个表issuestime_entries,它们之间有one-to-many个关联。我们可以为time_entries创建多个issue

这是一些示例数据,

问题

id  |  subject  |  description
------------------------------
1   |  test     |  test
2   |  test1    |  test1
3   |  test2    |  test2

时间条目

id  | issue_id  |  hours | spent_on   | created_on
---------------------------------------------------
1   |  1        |  2     | 2016-12-23 | 2016-12-23
2   |  1        |  2     | 2016-12-23 | 2016-12-23
3   |  2        |  3     | 2016-12-23 | 2016-12-23
4   |  2        |  5     | 2016-12-23 | 2016-12-23
5   |  4        |  4     | 2016-12-23 | 2016-12-23

现在我想获取在特定日期之后花费时间的所有issues

SELECT *
FROM "issues"
INNER JOIN "time_entries" ON "time_entries"."issue_id" = "issues"."id"
WHERE time_entries.created_on > '2016-12-22'

它返回了issues的多条记录,其中包含多个条目。

id   | subject  | description
-----------------------------
1   |  test     |  test
1   |  test     |  test
2   |  test1    |  test1
2   |  test1    |  test1
3   |  test2    |  test2

如何在不使用distinct的情况下避免这些重复记录。在我的申请中,由于技术原因,我无法使用distinct

任何帮助都将受到高度赞赏。

2 个答案:

答案 0 :(得分:2)

一种选择是使用SELECT DISTINCT

SELECT DISTINCT t1.id,
                t1.subject,
                t1.description
FROM issues t1
INNER JOIN time_entries t2
    ON t2.issue_id = t1.id
WHERE t2.created_on > '2016-12-22'

如果您不能使用DISTINCTGROUP BY,那么另一个选项是使用子查询来汇总time_entries表中的问题并确定哪些问题符合要求。像这样:

SELECT t1.id,
       t1.subject,
       t1.description
FROM issues t1
INNER JOIN
(
    SELECT issue_id
    FROM time_entries
    GROUP BY issue_id
    HAVING SUM(CASE WHEN created_on > '2016-12-22' THEN 1 ELSE 0 END) > 0
) t2
    ON t2.issue_id = t1.id

答案 1 :(得分:0)

SELECT * FROM "issues" 
INNER JOIN "time_entries" ON "time_entries"."issue_id" = "issues"."id"
WHERE time_entries.created_on > '2016-12-22' 
group by id