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

时间:2022-06-01 21:04:11
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 

ERROR MESSAGE: #1064 - 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 'UNION (SELECT J.act_id FROM Joinin J WHERE J.user_id = 'lhfcws')) ORDE' at line 7

错误消息:#1064 - 您的SQL语法出错;查看与MySQL服务器版本对应的手册,以便在'UNION(SELECT J.act_id FROM Joinin J WHERE J.user_id ='lhfcws')附近使用正确的语法)第7行的ORDE'

Activity(act_id, user_id, act_name)
Joinin(act_id, user_id)

Activity(act_id,user_id,act_name)Joinin(act_id,user_id)

2 个解决方案

#1


7  

The reason for your error is the parens around the select statements. You should write it as:

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

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

But do go over @Raphaël Althaus ideas for improving your query.

但请查看@RaphaëlAlthaus提出的改进查询的想法。

#2


2  

Hmm, don't think you need such a subquery

嗯,不要以为你需要这样一个子查询

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

sould do the same

也可以这样做

maybe you need one more check

也许你还需要一张支票

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);

Acording to @Jonathan Leffler's (true) remark

根据@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);

#1


7  

The reason for your error is the parens around the select statements. You should write it as:

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

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

But do go over @Raphaël Althaus ideas for improving your query.

但请查看@RaphaëlAlthaus提出的改进查询的想法。

#2


2  

Hmm, don't think you need such a subquery

嗯,不要以为你需要这样一个子查询

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

sould do the same

也可以这样做

maybe you need one more check

也许你还需要一张支票

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);

Acording to @Jonathan Leffler's (true) remark

根据@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);