Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax error in MySQL near UNION?

Tags:

syntax

sql

mysql

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

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

like image 698
Lhfcws Avatar asked May 09 '12 05:05

Lhfcws


People also ask

What is syntax error in MySQL?

The MySQL 1064 error is a syntax error. This means the reason there's a problem is because MySQL doesn't understand what you're asking it to do. However, there are many different situations that can lead to this type of miscommunication between you and your database.

Does MySQL support union operator?

Description. The MySQL UNION operator is used to combine the result sets of 2 or more SELECT statements. It removes duplicate rows between the various SELECT statements. Each SELECT statement within the UNION operator must have the same number of fields in the result sets with similar data types.

What does syntax error at or near mean?

This SQL error generally means that somewhere in the query, there is invalid syntax. Some common examples: Using a database-specific SQL for the wrong database (eg BigQuery supports DATE_ADD, but Redshift supports DATEADD) Typo in the SQL (missing comma, misspelled word, etc)


2 Answers

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

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.

like image 101
Ilion Avatar answered Sep 30 '22 17:09

Ilion


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

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);
like image 24
Raphaël Althaus Avatar answered Sep 30 '22 15:09

Raphaël Althaus