MySQL SELECT WHERE X喜欢和不喜欢B

时间:2013-05-24 00:48:08

标签: mysql select

我需要选择一些数据,但我无法按照我需要的方式进行操作,而我无法通过查询找到问题 数据如下:

user    | priority | group  
user-a  |    5     |  other  
user-b  |    5     |  none-a
user-b  |    2     |  some-grp
user-c  |    5     |  other-a  
user-d  |    5     |  other-b

基本上用户可以拥有多个具有优先级的组,并且我想过滤没有特定组的用户

使用的查询是:

SELECT * 
FROM tableName
WHERE group LIKE  "other%" OR group LIKE  "none%"
AND group NOT LIKE  "some%"
LIMIT 0 , 30  

但是这个查询会返回所有结果而不是用户a / c / d(它就像忽略了AND NOT LIKE

4 个答案:

答案 0 :(得分:1)

可能你想要这个:

SQL Fiddle

MySQL 5.5.30架构设置

create table t (`user` varchar(20), priority int, `group` varchar(20))
;
insert t (`user`, priority, `group`)
values ('user-a', 5, 'other'),
('user-b', 5, 'none-a'),
('user-b', 2, 'some-grp'),
('user-c', 5, 'other-a'),
('user-d', 5, 'other-b')

查询1

SELECT `user` 
FROM t
WHERE `user` in 
  (select `user` from t 
   where `group` LIKE  "other%" OR `group` LIKE  "none%")
   and `user` not in 
  (select `user` from t 
   where `group` LIKE  "some%")

<强> Results

|   USER |
----------
| user-a |
| user-c |
| user-d |

答案 1 :(得分:1)

如果您不想显示特定组中包含的用户,可以将 NOT IN与非相关子查询 NOT EXISTS与相关子查询策略一起使用

NOT IN与非相关子查询

SELECT `user`
FROM t
WHERE (`group` LIKE  "other%" OR `group` LIKE  "none%")
   AND `user` NOT IN (SELECT `user` FROM t WHERE `group` LIKE  "some%");

NOT EXISTS与相关子查询

SELECT t.`user`
FROM t
WHERE (t.`group` LIKE  "other%" OR t.`group` LIKE  "none%")
  AND NOT EXISTS 
  (
    SELECT 1 FROM t sub_t
    WHERE sub_t.`user` = t.`user`
      AND sub_t.`group` LIKE  "some%" );

答案 2 :(得分:0)

使用左连接,但只保留加入的行:

SELECT DISTINCT t1.*
FROM tableName t1
LEFT JOIN tableName t2
  ON t1.user_id = t2.user_id
  AND t2.group NOT LIKE "some%"
WHERE (t1.group LIKE  "other%"
OR t1.group LIKE  "none%")
AND t2.user_id IS NULL -- only non-joins
LIMIT 0, 30  

WHERE子句中还有一个错误,在括号中的OK条件(此处已修复)中由于运算符优先级而导致逻辑错误。

还必须猜测用户ID列是什么 - 您可能需要对此进行调整。

答案 3 :(得分:0)

我认为这是一个“set-within-sets”查询。我喜欢使用聚合和having来处理这些问题,因为这是一种非常灵活的方法。

select user
from t
group by user
having sum(group LIKE  'other%') > 0 or
       (sum(group LIKE 'none%' > 0 and
        sum(group like 'some%') = 0
       )

这基本上将where子句(在一条记录上操作)转换为having子句,该子句计算组中每个模式的出现次数。