【问题标题】:SQLite - Join returning duplicate resultSQLite - 加入返回重复结果
【发布时间】:2021-07-19 21:37:49
【问题描述】:

我已经阅读了数十篇关于此的帖子,如果很容易回答,我深表歉意,但我就是不明白。

表名:用户

user_id     group_id     house_name
==========================================
923828395   1            Alpha
722161580   2            Beta
923828395   1            Gamma

用户可以在多个组中,并且每个组在不同的房子中。

表格名称:点数

user_id     group_id     points   term_id
=====================================================================================
722161580   1            18       02078e51
923828395   1            11       02078e51
923828395   2            140      81450fc1

用户可以在其所在的每个Group中累积积分。在上面的数据中,user_id 923828395存在于group_id 1和2中,都在累积积分。

查询:

SELECT users.user_id, users.house_name, points.points, points.group_id, points.term_id
FROM users
JOIN points ON points.user_id = users.user_id
WHERE points.term_id = "02078e51" AND points.group_id = "1"

我试图让它只返回 2 行。但是它正在返回:

users.user_id     users.house_name points.points points.group_id points.term_id
722161580         Beta             18            1               02078e51
923828395         Alpha            11            1               02078e51
923828395         Gamma            11            1               02078e51

我认为这是因为我的 WHERE 有问题。我尝试将其翻转为 AND 语句,但得到相同的结果。

【问题讨论】:

    标签: sqlite join


    【解决方案1】:

    您还应该加入group_id 上的表格:

    SELECT u.user_id, u.house_name, p.points, p.group_id, p.term_id
    FROM users u JOIN points p
    ON p.user_id = u.user_id AND p.group_id = u.group_id
    WHERE p.term_id = '02078e51' AND p.group_id = '1'
    

    请参阅demo

    【讨论】:

    • 另外,感谢您提供指向 DBFiddle 的链接。以前没有遇到过,会让我的问题更简单!
    猜你喜欢
    • 2014-09-13
    • 1970-01-01
    • 2016-11-06
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多