[英]mysql join 2 tables - show all rows from one table
I have two tables, like so: table "a" contains:我有两个表,如下所示:表“a”包含:
id|name
stock1|fullname
stock2|fullname2
stock3|fullname3
table "b" contains product quantities for given stock.表“b”包含给定库存的产品数量。
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.现在我需要组合这两个表,以便每个产品从表“a”中获取其库存全名,如果没有为库存提供其数量,它仍将显示数量为 0 的行。
So from my example, product_id 13 would show as:因此,从我的示例中,product_id 13 将显示为:
stock|quanitity|product_id|stock_fullname
stock1|3|13|fullname1
stock2|0|13|fullname2
stock3|4|13|fullname3
You should be able to use a LEFT JOIN to achieve this.您应该能够使用 LEFT JOIN 来实现这一点。
SELECT a.id AS stock, COALESCE(b.quanitity,0), b.product_id, a.name AS stock_fullname
FROM a
LEFT JOIN b
ON a.id = b.stock_id
AND b.product_id = 13
You should be able to use a LEFT JOIN
to achieve this.您应该能够使用
LEFT JOIN
来实现这一点。
SELECT a.id AS stock, COALESCE(b.quanitity,0), b.product_id, a.name AS stock_fullname
FROM a
LEFT JOIN b
ON a.id = b.stock_id
AND b.product_id = 13
尝试这个:
SELECT stock,COALESCE(quanitity,0),product_id,stock_fullname FROM stock JOIN product
I think this query should work for your example:我认为此查询应该适用于您的示例:
SELECT a.id stock if(b.quantity IS NULL, 0, b.quantity),
b.product_id, a.name stock_fullname
FROM b
LEFT JOIN a b.stock = a.id
WHERE b.product_id = 13;
You need an outer join so that rows from the a table without a corresponding row in b are still considered.您需要一个外部联接,以便仍然考虑 a 表中没有 b 中相应行的行。 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.
如果从没有行的表中提取值,则会得到 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.
DB 之间的语法有所不同,并且根据是左侧还是右侧的表获取假行而有所不同。
see other answers for syntax.请参阅语法的其他答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.