尝试在使用 WHERE 语句时使用左连接从数据库获取所有结果
我做了一些研究,我认为我正在寻找的东西与我通过搜索找到的东西相反。
我目前正在尝试从一个表中提取一堆数据并将其与第二个表进行匹配。我正在使用左连接来完成此操作。我使用的代码是:
SELECT pn.id FROM pn
LEFT OUTER JOIN p ON pn.part_number = p.part_number
WHERE pn.programID = '13'
AND pn.visible = '1'
AND pn.type_id = '11'
AND (p.user_code = '01045' OR p.user_code IS NULL)
GROUP BY pn.part_number
ORDER BY p.quantity DESC LIMIT 0,25
只要用户代码与提供的值匹配或 p 表中不存在零件号,此查询就可以正常工作。我遇到的问题是,如果零件号位于 p 表中但位于不同的用户代码下,则不会提取零件号。
这不会成为问题,除非我需要显示 pn 表中的所有零件号,无论它们是否在 p 表中。 p 保存了我需要排序的数量,即使我想要 pn 表中的所有信息。
有谁知道如何从 pn 表中获取所有内容,同时仍然能够按 p.quantity 对信息进行排序,即使零件号匹配但用户代码不匹配?
谢谢! 安德鲁
I have done some research, and I think what I am looking for is kind of the opposite to what I've been able to find through searching.
I am currently trying to pull out a bunch of data from one table and match it up with a second. I am using a left join to accomplish this. The code I am using is:
SELECT pn.id FROM pn
LEFT OUTER JOIN p ON pn.part_number = p.part_number
WHERE pn.programID = '13'
AND pn.visible = '1'
AND pn.type_id = '11'
AND (p.user_code = '01045' OR p.user_code IS NULL)
GROUP BY pn.part_number
ORDER BY p.quantity DESC LIMIT 0,25
This query works great as long as the user code either matches the provided value or the part number doesn't exist in the p table. The problem I am encountering is that if the part number is in the p table but under a different user code, then the part number doesn't get pulled.
This wouldn't be a problem except I need to display all of the part numbers from the pn table regardless of if they're in the p table. The p holds the quantity which I need to sort by even though I want all the information from the pn table.
Does anyone have any idea how I can get everything from the pn table, while still being able to sort the information by p.quantity even if the part numbers match up but the user codes don't?
Thanks!
Andrew
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将
p.user_code
测试作为LEFT JOIN
条件的一部分,而不是在WHERE
子句中进行。Make the test for
p.user_code
part of theLEFT JOIN
condition instead of doing it in theWHERE
clause.