【问题标题】:Syntax error in MySQL near UNION?UNION附近的MySQL中的语法错误?
【发布时间】:2012-05-09 05:32:35
【问题描述】:
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)

【问题讨论】:

标签: mysql sql syntax


【解决方案1】:

您的错误的原因是选择语句周围的括号。你应该写成:

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ël Althaus 改进查询的想法。

【讨论】:

    【解决方案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);
    

    【讨论】:

    • UNION 是 OR;你的意思是 OR EXISTS?
    • 哇~!它的工作原理!非常感谢~~但我还是想知道为什么我错了~~
    【解决方案3】:

    不要在UNION

    之前使用ORDER BY

    【讨论】:

      猜你喜欢
      • 2017-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-16
      • 2018-08-21
      • 2017-01-12
      • 2014-03-12
      • 1970-01-01
      相关资源
      最近更新 更多