使用UNION和DISTINCT优化​​MySQL选择查询

时间:2017-07-03 14:47:56

标签: mysql database select distinct union

我的php脚本中有一个查询没有返回所需的数据。查询是

select distinct require_category from users_require

返回:

Diet
Experience
MeasurementsGain
MeasurementsLoss
MeasurementsMaintain
WeightGain
WeightLoss
WeightMaintain
Workout

但我只想要

Diet
Experience
MeasurementsGain
WeightGain
Workout

我已经改进了我的mysql查询并返回了corect结果,但我觉得它不够高效:

select distinct require_category from users_require where require_category NOT LIKE '%Weight%' and require_category NOT LIKE '%Measurements%' union select distinct require_category from users_require where require_category = 'WeightGain' or require_category = 'MeasurementsGain'

2 个答案:

答案 0 :(得分:3)

请尝试以下,

SELECT DISTINCT
require_category FROM users_require WHERE require_category NOT LIKE '%Loss%'
AND require_category NOT LIKE '%Maintain%'

答案 1 :(得分:0)

你可以使用一些联盟

  select min(require_category)
  from users_require
  where require_category like 'Measurements%';
  union 
  select min(require_category)
  from users_require
  where require_category like 'Weigh%';
  union 
  select require_category
  from users_require
  where require_category not like 'Measurements%' 
  and require_category not like 'Weigh%';