从两个表和 LEFT JOIN 结果中选择子集
我正在尝试为 SQLITE 编写一些 SQL,它将从两个表(TableA 和 TableB)中获取子集,然后执行 LEFT JOIN。
这是我尝试过的,但这会产生错误的结果:
Select * from TableA
Left Join TableB using(key)
where TableA.key2 = "xxxx"
AND TableB.key3 = "yyyy"
这会忽略 key2="xxxx" 但 key3 != "yyyy" 的情况。
我希望 TableA 中的所有行都符合我的条件,无论 TableB 中的相应值是否匹配,但只希望 TableB 中符合这两个条件的行。
我确实设法通过使用 VIEW 来解决这个问题,但我确信一定有更好的方法来做到这一点。现在我正开始疯狂地尝试解决它。
(感谢您的帮助,希望我已经解释得足够好)。
I'm trying to write a bit of SQL for SQLITE that will take a subset from two tables (TableA and TableB) and then perform a LEFT JOIN.
This is what I've tried, but this produces the wrong result:
Select * from TableA
Left Join TableB using(key)
where TableA.key2 = "xxxx"
AND TableB.key3 = "yyyy"
This ignore cases where key2="xxxx" but key3 != "yyyy".
I want all the rows from TableA that match my criteria whether or not their corresponding value in TableB matches, but only those rows from TableB that match both conditions.
I did manage to solve this by using a VIEW, but I'm sure there must be a better way of doing this. It's just beginning to drive me insane tryng to solve it now.
(Thanks for any help, hope I've explained this well enough).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你犯了经典的左连接错误。在大多数数据库中,如果您想在左联接右侧的表上设置条件,则必须将此条件放在联接本身中,而不是放在 where 子句中。在 SQL Server 中,这会将左联接变成内联接。我没有使用过 SQl lite,所以我不知道它是否具有相同的功能,但所有记录通常都必须满足 where 子句。
YOu have made the classic left join mistake. In most databases if you want a condition on the table on the right side of the left join you must put this condition in the join itself and NOT the where clause. IN SQL Server this would turn the left join into an inner join. I've not used SQl lite so I don't know if it does the same but all records must meet the where clause generally.