在UNION附近的MySQL中的語法錯誤?

[英]Syntax error in MySQL near UNION?


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

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/05/09/2519c677f7134567032a0ff2ea04f71d.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com