所以我试图列出每个客户的数量和名称,这些客户由销售代表65代表,或者当前有订单存在,或者两者都有,并且我一直收到错误。我甚至检查了书中的解决方案,我的代码看起来一样。这个错误告诉我什么?我附上了本书给出的解决方案。 Solution
mysql> SELECT CUSTOMER_NUM, CUSTOMER_NAME
-> FROM CUSTOMER
-> WHERE REP_NUM+'65'
-> UNION
-> SELECT C.CUSTOMER_NUM, CUSTOMER_NAME
-> FROM CUSTOMER C, ORDERS 0
-> WHERE C.CUSTOMER_NUM=0.CUSTOMER_NUM;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '0
WHERE C.CUSTOMER_NUM=0.CUSTOMER_NUM' at line 6
答案 0 :(得分:2)
您有zero
作为别名,这是出错的原因。数字不允许别名。我认为您o
而不是zero
SELECT CUSTOMER_NUM, CUSTOMER_NAME
FROM CUSTOMER
WHERE REP_NUM = '65' -- also here `=` should be used instead of `+`
UNION
SELECT C.CUSTOMER_NUM, CUSTOMER_NAME
FROM CUSTOMER C, ORDERS o
WHERE C.CUSTOMER_NUM=o.CUSTOMER_NUM;
答案 1 :(得分:1)
使用EXISTS
:
select c.*
from customer c
where rep_num = 65 or
exists (select 1 from orders o where c.customer_num = o.customer_num);
您的具体问题是您使用了数字作为表别名。你应该真的在用一封信。
然而,其他一些事情浮现在脑海中:
union
是一种资源匮乏,因为它会导致删除重复项的开销。这个查询不是必需的。65
,不应该用单引号括起来 - 这些数字应该用于字符串和日期。+
,其中要求=
。答案 2 :(得分:1)
检查你的语法,它是='65'而不是+ '65'
mysql> SELECT CUSTOMER_NUM, CUSTOMER_NAME
-> FROM CUSTOMER
-> **WHERE REP_NUM+'65**'
-> UNION
-> SELECT C.CUSTOMER_NUM, CUSTOMER_NAME
-> FROM CUSTOMER C, ORDERS 0
-> WHERE C.CUSTOMER_NUM=0.CUSTOMER_NUM;