Union - 相同的表,不包括以前的结果MySQL

时间:2012-12-18 23:00:57

标签: mysql

我试图编写一个查询:

  • 运行查询,给我(x)行数(限制4)
  • 如果该查询没有给出我需要的4个,请运行第二个查询限制4-(x)并从第一个查询中排除ID
  • 第三个查询,就像第二个
  • 一样

我有这个:

(SELECT *, 1 as SORY_QUERY1 FROM xbamZ where state = 'Minnesota' and industry = 'Miscellaneous' and id != '229' limit 4) 
UNION 
(SELECT *, 2 FROM xbamZ where state = 'Minnesota' limit 2) 
UNION 
(SELECT *, 3 FROM xbamZ where industry = 'Miscellaneous' limit 1)

我是如何(或是?)这样做的?我接近了吗?这个查询给了我重复

1 个答案:

答案 0 :(得分:2)

我认为不需要工会和三个select。一个人也会工作

SELECT a.*
FROM
(
SELECT xbamZ.*,
CASE 
  WHEN state = 'Minnesota' and industry = 'Miscellaneous' and id != '229' THEN 1
  WHEN state = 'Minnesota' THEN 2
  WHEN industry = 'Miscellaneous' THEN 3
END as rnk
FROM xbamZ 
where state = 'Minnesota' or industry = 'Miscellaneous' 
)a 
ORDER BY rnk
LIMIT 4;