在UNION附近的MySQL中的语法错误?

时间:2012-05-09 05:32:36

标签: mysql sql syntax

SELECT * 
FROM Activity AA
WHERE AA.act_id IN 
((SELECT A.act_id 
  FROM Activity A 
  WHERE A.user_id = 'lhfcws')
 UNION
 (SELECT J.act_id 
  FROM Joinin J 
  WHERE J.user_id = 'lhfcws'))
ORDER BY AA.act_time 
  

错误消息:   #1064 - 您的SQL语法有错误;检查与MySQL服务器版本对应的手册,以获得正确的语法   靠近'UNION (SELECT J.act_id FROM Joinin J WHERE J.user_id = 'lhfcws')) ORDE' at line 7

活动(act_id,user_id,act_name)
加入(act_id,user_id)

3 个答案:

答案 0 :(得分:7)

错误的原因是select语句周围的问题。你应该把它写成:

SELECT * 
FROM Activity AA
WHERE AA.act_id IN 
(SELECT A.act_id 
  FROM Activity A 
  WHERE A.user_id = 'lhfcws'
 UNION
 SELECT J.act_id 
  FROM Joinin J 
  WHERE J.user_id = 'lhfcws')
ORDER BY AA.act_time

但请查看@RaphaëlAlthaus改善查询的想法。

答案 1 :(得分:2)

嗯,不要认为你需要这样的子查询

select * from Activity a
where a.user_id = 'lhfcws'
and exists (select null from Joinin j
where a.user_id = j.user_id);

可以做同样的事情

也许你需要再检查一次

select * from Activity a
    where a.user_id = 'lhfcws'
    and exists (select null from Joinin j
    where a.user_id = j.user_id
    and a.act_id = j.act_id);

根据@Jonathan Leffler的(真实)评论

select * from Activity a
        where a.user_id = 'lhfcws'
        or exists (select null from Joinin j
        where j.user_id = 'lhfcws'
        and a.act_id = j.act_id);

答案 2 :(得分:-1)

不要在 UNION

之前使用 ORDER BY