Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an overall WHERE clause when using UNIONS in sql

I am trying to return the MATCH() AGAINST() results against several tables using UNIONS, the only problem is some rows return a relevance of 0, I want to exclude these. After the unions is there a way to use 'WHERE relevance > 0'

Below is a bit of my SQL

SELECT pages.content AS search, page_info.url AS link, MATCH(pages.content) AGAINST('Wales') as relevance 
FROM page_content
LEFT JOIN pages ON (page_info.page = pages.id)

UNION

SELECT products_real.name AS search, products_real.event AS link, MATCH(products_real.name, products_real.description) AGAINST ('Wales') as relevance
FROM product_real

ORDER BY relevance DESC

So is there anyway I can add WHERE relevance > 0 before the ORDER BY

many thanks

like image 600
wiggles Avatar asked Jul 07 '10 13:07

wiggles


2 Answers

Try using a derived table

SELECT * 
FROM
  (SELECT 
    pages.content AS search, 
    page_info.url AS link, 
    MATCH(pages.content) AGAINST('Wales') as relevance  
  FROM page_content 
  LEFT JOIN pages ON (page_info.page = pages.id) 
  UNION 
  SELECT 
    products_real.name AS search, 
    products_real.event AS link, 
    MATCH(products_real.name, products_real.description) AGAINST ('Wales') as relevance 
  FROM product_real) myQuery
Where myQuery.relevance <> 0
ORDER BY myQuery.relevance DESC
like image 179
John Hartsock Avatar answered Oct 10 '22 07:10

John Hartsock


you could add it to each query or at the end:

SELECT pages.content AS search, page_info.url AS link, MATCH(pages.content) AGAINST('Wales') as relevance 
FROM page_content
LEFT JOIN pages ON (page_info.page = pages.id)
WHERE relevance > 0

UNION

SELECT products_real.name AS search, products_real.event AS link, MATCH(products_real.name, products_real.description) AGAINST ('Wales') as relevance
FROM product_real
WHERE relevance > 0

ORDER BY relevance DESC



SELECT search, relevance FROM
(

SELECT pages.content AS search, page_info.url AS link, MATCH(pages.content) AGAINST('Wales') as relevance 
FROM page_content
LEFT JOIN pages ON (page_info.page = pages.id)

UNION

SELECT products_real.name AS search, products_real.event AS link, MATCH(products_real.name, products_real.description) AGAINST ('Wales') as relevance
FROM product_real
) D
WHERE relevance > 0
ORDER BY relevance DESC
like image 40
souLTower Avatar answered Oct 10 '22 08:10

souLTower