【问题标题】:Inner join return only the first matching Row内连接只返回第一个匹配的行
【发布时间】:2014-04-16 15:58:28
【问题描述】:

我在网站和谷歌上到处找,没有找到我正在寻找的答案,我有 2 个表格,每个表格都有具体信息,报告给出了重复 我需要获取名称、反馈 ID 和最多具有 1 个反馈 ID 的站点。

这是我的 2 张桌子

表:反馈

userID              | ID 
john.smith          |1
george.wilson       |2
justin.example      |3
justin.example      |4
juliana.something   |5
george.wilson       |6

表:用户(此表上的其他信息给出了重复的原因)

UserID              |Site
george.wilson       |location 1
george.wilson       |location 1
george.wilson       |location 1
john.smith          |Location 2
john.smith          |Location 2
juliana.something   |Location 3
justin.example      |Location 4
justin.example      |Location 4

当前查询

SELECT feedback.userID,  feedback.id, Users.Site        
FROM feedback       
INNER JOIN users ON     
feedback.userID = users.userid      
WHERE feedback.userID <> 'x'

当前结果

UserID              |ID | Sites
john.smith          |1  |Location 2
john.smith          |1  |Location 2
george.wilson       |2  |location 1
george.wilson       |2  |location 1
george.wilson       |2  |location 1
justin.example      |3  |Location 4
justin.example      |3  |Location 4
justin.example      |4  |Location 4
justin.example      |4  |Location 4
juliana.something   |5  |Location 3
george.wilson       |6  |location 1
george.wilson       |6  |location 1
george.wilson       |6  |location 1

预期结果

UserID              |ID | Sites
john.smith          |1  |Location 2
george.wilson       |2  |location 1
justin.example      |3  |Location 4
justin.example      |4  |Location 4
juliana.something   |5  |Location 3
george.wilson       |6  |location 1

我的查询已最小化,需要更多内容,但错误来自我的“内部联接”用户,谁能帮我解决这个问题? (我正在使用 My Sql Workbench 6.0) 提前谢谢你!

【问题讨论】:

  • 选择不同的 feedback.userID、feedback.id、Users.Site

标签: mysql sql select join inner-join


【解决方案1】:

您可以使用limit 子句来限制行数:

SELECT     f.userID, f.id, u.site
FROM       feedback f
INNER JOIN (SELECT   userID, site
            FROM     users
            ORDER BY site DESC
            LIMIT    1) u ON g.userID = u.userID
WHERE      f.userID <> 'x'

【讨论】:

  • 嗨,谢谢你的帮助,我试过了,我相信这个查询离成功只有一小步,我得到 0 行返回,而没有加入我的网站和用户表我得到 188行(预期的结果,但有网站呵呵)还在您的查询中添加了 g.userID 它指的是什么?再次感谢您。
【解决方案2】:

问题是重复的数据。 SQL 不知道也不关心它为什么在表中重复,它只会返回与您的查询完全匹配的所有内容。这是一个非常简单的查询,因此只需添加 DISTINCT 即可消除重复行,而无需任何额外的奇怪连接。

SELECT DISTINCT feedback.userID,  feedback.id, users.Site
FROM feedback, users
WHERE feedback.userID = users.userid      
AND feedback.userID <> 'x'

【讨论】:

  • 有了不同的,我只得到 88 行,而我应该得到 188 行返回,我已经尝试过了,但它过滤了更多它应该过滤的东西,我不知道删除了什么,这是一个好主意,但我的查询要大得多,看起来它找到重复的信息而不是重复的行。我真正的查询查看了 5 个不同的表......有没有办法将一个不同的指向 1 个表的只有 1 列,即我的没有 distinct 的查询给了我 2820 行,如果在我的结果之后它可以过滤这些数据并只保留每个 feedback.ID 中的一个就可以了。
猜你喜欢
  • 2014-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多