开发者

Using an overall WHERE clause when using UNIONS in sql

I am trying to return the MATCH() AGAINST() 开发者_JS百科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


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜