尝试在使用 WHERE 语句时使用左连接从数据库获取所有结果

发布于 2024-10-30 05:54:43 字数 647 浏览 0 评论 0原文

我做了一些研究,我认为我正在寻找的东西与我通过搜索找到的东西相反。

我目前正在尝试从一个表中提取一堆数据并将其与第二个表进行匹配。我正在使用左连接来完成此操作。我使用的代码是:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

十六岁半 2024-11-06 05:54:43

p.user_code 测试作为 LEFT JOIN 条件的一部分,而不是在 WHERE 子句中进行。

SELECT pn.id FROM pn 
LEFT OUTER JOIN p ON pn.part_number = p.part_number 
    AND p.user_code = '01045'
WHERE pn.programID = '13' 
AND pn.visible = '1' 
AND pn.type_id = '11' 
GROUP BY pn.part_number 
ORDER BY p.quantity DESC LIMIT 0,25 

Make the test for p.user_code part of the LEFT JOIN condition instead of doing it in the WHERE clause.

SELECT pn.id FROM pn 
LEFT OUTER JOIN p ON pn.part_number = p.part_number 
    AND p.user_code = '01045'
WHERE pn.programID = '13' 
AND pn.visible = '1' 
AND pn.type_id = '11' 
GROUP BY pn.part_number 
ORDER BY p.quantity DESC LIMIT 0,25 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文