我目前正在为本地站点进行一些嵌入式SQL查询。我陷入困惑。我需要这样做“向用户询问制造商。打印该制造商的所有产品的规格。即打印型号,产品类型以及适合该类型的任何关系的所有属性。”
我尝试了以下查询
(SELECT * FROM product NATURAL JOIN pc WHERE maker = '$m')
union (SELECT * FROM product NATURAL JOIN printer WHERE maker = '$m')
union (SELECT * FROM product NATURAL JOIN laptop WHERE maker = '$m');
但问题是每个表(个人电脑,笔记本电脑,打印机)没有相同的列。我认为如果表中没有包含该列,只需填写空值就可以解决我的问题。我试图将所有表和列合并到一个超级表中并将其显示给用户。然后我也想尝试按产品类型订购大表。我认为我只会在查询结束时给出一个ORDER BY。所以我的问题是如何加入这些表?
关系:
Product(maker, model, type (laptop, printer, pc))
Printer(model, color (0,1), type(ink-jet, laser), price)
Laptop(model, speed, ram, hd, screen, price)
Pc(model, speed, ram hd, price)
答案 0 :(得分:0)
查看“SQL表别名”以使用较少的列向表中添加列。或者您可以输入空值,如:
Select Col1, Col2, Col3 from Table1
Union
Select Col1, Null as Col2, Null as Col3 from Table2
答案 1 :(得分:0)
是的,您可以使用UNION来完成这项工作。只需使所有SELECT列表具有相同的名称和相同的类型,如下所示:
SELECT (a,b) FROM TABLE TableB NATURAL JOIN (
SELECT a,b,c, NULL as d from TableC
UNION
SELECT a,b,NULL as c, d from TableD
) AS u ON u.b = TableB.b
答案 2 :(得分:0)
您只需为不存在的字段选择NULL值。
(SELECT maker,pc.model,p.model,price,NULL AS color,speed,pc.type,pc.type,ram,hd,NULL AS screen
FROM product p NATURAL JOIN pc WHERE maker = '$m')
UNION
(SELECT maker,printer.model,p.model,price,color,NULL AS speed,printer.type,p.type,NULL AS ram,NULL AS hd,NULL AS screen
FROM product p NATURAL JOIN printer WHERE maker = '$m')
UNION
(SELECT maker,laptop.model,p.model,price,NULL AS color,speed,laptop.type,laptop.type,ram,hd,screen
FROM product p NATURAL JOIN laptop WHERE maker = '$m');
答案 3 :(得分:-1)
我认为你的意思是使用join关键字,而不是union关键字。