1

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

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

4 回答 4

1

可能你想要这个:

SQL小提琴

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%")

结果

|   USER |
----------
| user-a |
| user-c |
| user-d |
于 2013-05-24T01:29:19.730 回答
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%");

不存在相关子查询

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%" );
于 2013-05-24T02:26:48.003 回答
0

I think this is a "set-within-sets" query. I like to approach these using aggregation and having, because that is a very flexible approach.

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
       )

This basically translates your where clause -- which operates on one record -- in a having clause that counts the occurrences of each pattern in the group.

于 2013-05-24T02:55:31.650 回答
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 列是什么——您可能需要对此进行调整。

于 2013-05-24T02:38:44.123 回答