0

我正在尝试编写一个查询,它将:

  • 运行查询,给我 (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)

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

4

1 回答 1

2

我认为没有必要 union 和三个selects。一个也可以

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;
于 2012-12-18T23:07:22.417 回答