我试图找到两台或多台不同电脑(PC和/或笔记本电脑)的制造商,其中“HD”大于或等于10。
产品有:制造商&模型
PC和PC都是笔记本电脑有:型号& HD这是我到目前为止所写的:
SELECT DISTINCT maker
FROM
(
(
SELECT model, maker
FROM
(SELECT model FROM laptop WHERE hd >= 10) AS lap2
NATURAL JOIN product
) as ta
UNION ALL
(
SELECT model, maker
FROM
(SELECT model FROM pc WHERE hd >= 10) AS pc2
NATURAL JOIN product
) AS tb
) AS t1
JOIN t1 as t2
ON (t1.model != t2.model and t1.model > t2.model)
然而,它为我提供了一个可爱的错误:
1064 - 您的SQL语法出错;查看与您的MySQL服务器版本对应的手册,以便在'AS tb附近使用正确的语法AS t1 JOIN t1 as t2 ON(t1.model!= t2.model和t1.model> t2.model)'at line 16
工件:
SELECT model, maker
FROM
(SELECT model FROM laptop WHERE hd >= 10) AS lap2
NATURAL JOIN product
SELECT model, maker
FROM
(SELECT model FROM pc WHERE hd >= 10) AS pc2
NATURAL JOIN product
答案 0 :(得分:3)
由于你的括号是平衡的,我不认为“太多括号”是问题所在。
问题出在
JOIN t1 AS t2
您有t1
作为UNION查询;你不能轻易地将t1
作为一个表而不会让所有人感到困惑。
您可以写:
JOIN t3 AS t2
其中t3
是DBMS中的表(或视图)。
顺便提一下,你的ON条件不需要两个条件:
ON (t1.model != t2.model AND t1.model > t2.model)
使用:
就足够了ON (t1.model > t2.model)
如果你想在UNION上进行自联接,你必须两次编写UNION,或者(如果MySQL支持它,我认为它没有)CTE(公用表表达式),在主SQL语句之前称为WITH子句:
WITH t1(model, maker) AS
(SELECT model, maker
FROM (SELECT model FROM laptop WHERE hd >= 10) AS lap2
NATURAL JOIN product
UNION ALL
SELECT model, maker
FROM (SELECT model FROM pc WHERE hd >= 10) AS pc2
NATURAL JOIN product
)
SELECT DISTINCT t1a.maker
FROM t1 AS t1a
JOIN t1 AS t1b ON (t1a.model > t1b.model)
我不太清楚ON状况意味着什么;它似乎有利于斑马而不是土豚,但这就是全部。但是,这在语法上(近似)是正确的。
如果没有WITH子句,则将表达式写出两次:
SELECT DISTINCT t1a.maker
FROM (SELECT model, maker
FROM (SELECT model FROM laptop WHERE hd >= 10) AS lap2
NATURAL JOIN product
UNION ALL
SELECT model, maker
FROM (SELECT model FROM pc WHERE hd >= 10) AS pc2
NATURAL JOIN product
) AS t1a
JOIN (SELECT model, maker
FROM (SELECT model FROM laptop WHERE hd >= 10) AS lap2
NATURAL JOIN product
UNION ALL
SELECT model, maker
FROM (SELECT model FROM pc WHERE hd >= 10) AS pc2
NATURAL JOIN product
) AS t1b
ON (t1a.model > t1b.model)
当然,这只是对您的查询的解释。你的问题似乎更简单:
SELECT Maker
FROM (SELECT model, maker
FROM (SELECT model FROM laptop WHERE hd >= 10) AS lap2
NATURAL JOIN product
UNION ALL
SELECT model, maker
FROM (SELECT model FROM pc WHERE hd >= 10) AS pc2
NATURAL JOIN product
) AS t -- per comment (and SQL standard, but it really is superfluous!)
GROUP BY Maker
HAVING COUNT(*) > 1;