2

我目前正在为本地站点处理一些嵌入式 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)
4

4 回答 4

0

查看“SQL 表别名”以将列添加到具有较少列的表中。或者您也可以输入空值,例如:

Select Col1, Col2, Col3 from Table1
Union
Select Col1, Null as Col2, Null as Col3 from Table2
于 2012-05-16T16:45:24.047 回答
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
于 2012-05-16T16:46:02.027 回答
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');
于 2012-05-16T16:49:34.673 回答
-1

我认为您的意思是使用 join 关键字,而不是 union 关键字。

看看http://dev.mysql.com/doc/refman/5.0/en/join.html

于 2012-05-16T16:41:25.133 回答