Question

So I'm trying to join 4 subqueries with a Union in MySQL and I can't figure it out.

Below are the 4 subqueries. I need to union the first 2 with the last 2.

when I try to UNION the 4 I get a syntax error. Do I need to change the code for the subqueries?

  SELECT Title, AlbumDescription FROM Albums WHERE
  MATCH(AlbumDescription)                            
  AGAINST('blondes');

  SELECT Title, AlbumDescription FROM Albums WHERE MATCH(AlbumDescription)                                        
  AGAINST('bodybags'); 

  SELECT Title, AlbumDescription FROM Albums WHERE MATCH(AlbumDescrption)                             
  AGAINST('fireplaces' WITH QUERY EXPANSION);     

  SELECT Title, AlbumDescription FROM Albums WHERE MATCH(AlbumDescription)                                        
  AGAINST('sighing' WITH QUERY EXPANSION);
SELECT Title, AlbumDescription FROM Albums  WHERE
MATCH(AlbumDescription)  
  AGAINST('blondes') 

SELECT Title, AlbumDescription FROM Albums  WHERE
MATCH(AlbumDescription)  
  AGAINST('bodybags')

UNION

SELECT Title, AlbumDescription FROM Albums  WHERE
MATCH(AlbumDescription)  
  AGAINST('fireplaces' WITH QUERY EXPANSION) 

SELECT Title, AlbumDescription FROM Albums  WHERE
MATCH(AlbumDescription)  
  AGAINST('sighing' WITH QUERY EXPANSION);

I used the syntax above and I am getting an error saying I have a syntax error near line 3. For some reason there are indents where AGAINST is in the syntax on here, but it is not in my actual code.

Was it helpful?

Solution

Why would you need to use UNION?

The queries are all against the same table; do it as a single SELECT against the table. Use AND and/or OR logical operators to combine the predicates.

To get rows from the table that satisfy any of the conditions:

SELECT a.Title
     , a.AlbumDescription
  FROM Albums a 
 WHERE MATCH(a.AlbumDescription) AGAINST('blondes') 
    OR MATCH(a.AlbumDescription) AGAINST('bodybags')
    OR MATCH(a.AlbumDescription) AGAINST('fireplaces' WITH QUERY EXPANSION)
    OR MATCH(a.AlbumDescription) AGAINST('sighing' WITH QUERY EXPANSION)

Here's an example of the UNION set operator to combine the results from four queries:

SELECT a.Title
     , a.AlbumDescription
  FROM Albums a 
 WHERE MATCH(a.AlbumDescription) AGAINST('blondes') 
 UNION
SELECT a.Title
     , a.AlbumDescription
  FROM Albums a 
 WHERE MATCH(a.AlbumDescription) AGAINST('bodybags')
 UNION
SELECT a.Title
     , a.AlbumDescription
  FROM Albums a 
 WHERE MATCH(a.AlbumDescription) AGAINST('sighing' WITH QUERY EXPANSION)
 UNION
SELECT a.Title
     , a.AlbumDescription
  FROM Albums a 
 WHERE MATCH(a.AlbumDescription) AGAINST('sighing' WITH QUERY EXPANSION)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top