我有3个表,这些表将合并为1个表。
表1
id|prdct_name|qty
001 A 5
002 B 5
003 C 5
table2
id|prdct_id|price
1 001 100
2 001 200
3 002 150
4 002 250
table3
id|prdct_id|stock_in|stock_out
1 001 5 0
2 001 10 0
3 002 15 0
4 002 25 0
我已经尝试过此sql(由于输入错误而更新)
select a.prdct_name as Name, a.qty as QTY,b.price as PRICE, c.stock_in as SIN,c.stock_out as SOUT
from table1 a
left join table2 b on a.id=b.prdct_id
left join table3 c on a.id=c.prdct_id
where 1=1 group by b.id,c.id
但结果返回与此表相同的重复
NAME|QTY|PRICE|SIN|SOUT
A 5 100 5 0
A 5 100 10 0
A 5 200 5 0
A 5 200 10 0
B 5 150 15 0
B 5 150 25 0
B 5 250 15 0
B 5 250 25 0
结果应该是
NAME|QTY|PRICE|SIN|SOUT
A 5 100 5 0
A 5 200 10 0
B 5 150 15 0
B 5 250 25 0
是否有办法消除重复的问题?尝试与众不同也无济于事。 谢谢
答案 0 :(得分:1)
看起来您的第二个join
应该在id
上-并且您的join
条件看起来也不正确。
select a.prdct_name as Name, a.qty as QTY, b.price as PRICE, c.stock_in as SIN,c.stock_out as SOUT
from table1 a left join
table2 b
on a.id = b.prdct_id left join
table3 c
on a.id = c.id
where 1=1
group by b.id, c.id
答案 1 :(得分:1)
更改您的连接密钥,它应为id = product_id,但您尝试使用名称和product_id
select a.prdct_name as Name, a.qty as QTY,b.price as PRICE, c.stock_in as SIN,c.stock_out as SOUT
from table1 a
left join table2 b on a.id=b.prdct_id
left join table3 c on a.id=c.prdct_id
where 1=1 group by b.id,c.id
答案 2 :(得分:0)
您可以使用SQL关键字DISTINCT
选择不重复的行。
示例:
SELECT DISTINCT
prdct_name as NAME,
qty as QTY,
price as PRICE,
stock_in as SIN,
stock_out as SOUT
FROM
table1 a
INNER JOIN
table2 b ON a.id=b.prdct_id
LEFT JOIN
table3 c ON b.id=c.id
GROUP BY
a.id, c.id
有关 DISTINCT here的更多信息。