mysql 连接 2 个表 - 显示一张表中的所有行
我有两张表,如下所示: 表“a”包含:
id|name
stock1|fullname
stock2|fullname2
stock3|fullname3
表“b”包含给定库存的产品数量。
id|stock_id|quantity|product_id|
1|stock1|3|13
2|stock3|4|13
3|stock1|1|5
4|stock2|2|2
现在我需要合并这两个表,以便每个产品从表“a”中获取其库存全名,如果没有给出库存数量,它仍然会显示数量为 0 的行。
所以从我的例如,product_id 13 将显示为:
stock|quanitity|product_id|stock_fullname
stock1|3|13|fullname1
stock2|0|13|fullname2
stock3|4|13|fullname3
I have two tables, like so:
table "a" contains:
id|name
stock1|fullname
stock2|fullname2
stock3|fullname3
table "b" contains product quantities for given stock.
id|stock_id|quantity|product_id|
1|stock1|3|13
2|stock3|4|13
3|stock1|1|5
4|stock2|2|2
Now I would need to combine those two tables, so that each product takes its stock full name from table "a", and if its quanitity is not given for stock, it would still show the row with the quanitity as 0.
So from my example, product_id 13 would show as:
stock|quanitity|product_id|stock_fullname
stock1|3|13|fullname1
stock2|0|13|fullname2
stock3|4|13|fullname3
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您应该能够使用 LEFT JOIN 来实现此目的。
You should be able to use a LEFT JOIN to achieve this.
听起来您需要使用 LEFT JOIN,尽管记录任何数量都可能显示为 NULL 而不是零。像这样的东西:
It sounds like you need to use a LEFT JOIN, although the records with no quantity might show as NULL rather than zero. Something like:
试试这个:
try this:
您需要一个外连接,以便仍考虑 a 表中没有 b 中对应行的行。相比之下,内部联接坚持认为您有匹配的行。如果从没有行的表中提取值,则会得到 NULL。数据库之间的语法有所不同,并且根据是左侧表还是右侧表获取假行来进行区分。
有关语法,请参阅其他答案。
You need an outer join so that rows from the a table without a corresponding row in b are still considered. An inner join, by contrast, insists that you have a matching row. If you are pulling a value from the table where you don't have a row, you get NULL. Syntax varies between DBs and there is a distinction made depending on if it's the table on the left or right that gets the fake rows.
see other answers for syntax.
我认为这个查询应该适用于您的示例:
I think this query should work for your example:
您应该能够使用
LEFT JOIN
来实现这一点。You should be able to use a
LEFT JOIN
to achieve this.