sql执行3自然连接然后联合然后在一起

时间:2019-02-01 17:39:05

标签: sql syntax

我想自然加入3次(Product是库存),然后将它们合并在一起,但是以下内容没有错误near "(": syntax error: (,我想看看model和{{ 1}}个匹配项。

price

有人可以帮忙吗?谢谢。

4 个答案:

答案 0 :(得分:0)

可能是你有太多的()ADN缺少表的别名

SELECT model, price 
FROM PC  
NATURAL JOIN ( SELECT model FROM Product WHERE maker='B') t1

UNION

SELECT model, price 
FROM Laptot 
NATURAL JOIN (SELECT model FROM Product WHERE maker='B') t2

UNION

SELECT model, price 
FROM Printer 
NATURAL JOIN (SELECT model FROM Product WHERE maker='B') t3;

如果您不是自然联接而是要使用内部联接,则可以看到表名alais用于正确识别与列相关的e:

SELECT model, price 
FROM Printer 
INNER JOIN ( 
  SELECT model FROM Product WHERE maker='B'
) t3 on t3.model = printer.model ;

答案 1 :(得分:0)

您可以像下面这样编写查询

select
model, price from (SELECT model, price FROM PC) a1 JOIN 
(SELECT model FROM Product WHERE maker='B') a on a1.model=a.model 

union
 select model, price from
(SELECT model, price FROM Laptop) b1
JOIN (SELECT model FROM Product WHERE maker='B') b on b1.model =b.model 
UNION
 select model, price from
(SELECT model, price FROM Printer) c1 JOIN
(SELECT model FROM Product WHERE maker='B') c on c1.model=c.model

答案 2 :(得分:0)

JOIN(及其变体)是FROM子句中的 operators 。因此,您的查询根本没有意义。您在有意义的SQL子句之外使用运算符。

每个查询可以编写为:

select model, price
from (SELECT model, price FROM PC) p NATURAL JOIN
     (SELECT model FROM Product WHERE maker ='B') b;

但是,我认为NATURAL JOIN是可憎的,因为它通过名称而不是通过明确的外键关系匹配列。此用法比大多数用法略好。该代码明确地选择了这些列,因此该代码与使逻辑混乱的“意外”列隔离开来。

但是,我认为这更简单明了:

select p.model, p.price
from pc p join
     product pr
     on p.model = pr.mode
where pr.maker = 'B';

exists可能更清晰:

select p.model, p.price
from pc p join
where exists (select 1
              from product pr
              where p.model = pr.model and pr.maker = 'B'
             );

答案 3 :(得分:0)

三个表的联合然后是第四个的半联接怎么办?:

WITH T AS ( SELECT model, price FROM PC 
            UNION 
            SELECT model, price FROM Laptop 
            UNION 
            SELECT model, price FROM Printer )
SELECT * 
  FROM T 
 WHERE model IN ( SELECT model FROM Product WHERE maker = 'B' );