如果user_id包含特定代码,则跳过行

时间:2018-08-14 14:47:06

标签: mysql

我有这些行

 user_id   code
    1      9103 
    1      9103 
    1      9001
    2      9103
    3      9103
    3      9104
    4      9103
    4      9103
    4      9001

我只想获取不包含9001的ID,然后仅包含2和3 我尝试了Distinct,但我没有幸运

Select distinct v.code, user_id from mytable as v
    where v.code not in ( Select v2.code from mytable as v2
    where v2.code=9001)

2 个答案:

答案 0 :(得分:4)

按用户分组,然后仅接受没有条件记录的分组

select user_id
from your_table
group by user_id
having sum(code = 9001) = 0

答案 1 :(得分:1)

有多种方法可以获取所需的结果。

不存在(所有DBMS)

SELECT 
 *
FROM 
 Table1
WHERE
 NOT EXISTS (
  SELECT 
   1
  FROM 
   Table1
  WHERE 
   code = 9001
)

不能进入(所有DBMS)

SELECT
 DISTINCT 
  Table1.user_id
FROM 
 Table1 
WHERE
 user_id NOT IN (

  SELECT
   user_id
  FROM 
   Table1
  WHERE
   code = 9001

)

RIGHT JOIN / LEFT JOIN(所有DBMS,但例如SQLite不支持RIGHT JOIN)

SELECT 
 DISTINCT
  Table1.user_id
FROM (
  SELECT
   user_id
  FROM 
   Table1
  WHERE
   code = 9001
) AS Table1_filter
RIGHT JOIN 
 Table1
ON
 Table1_filter.user_id = Table1.user_id
WHERE
 Table1_filter.user_id IS NULL

;

SELECT 
  DISTINCT
    Table1.user_id
FROM 
 Table1 
LEFT JOIN  (
  SELECT
   user_id
  FROM 
   Table1
  WHERE
   code = 9001
) AS Table1_filter
ON
 Table1_filter.user_id = Table1.user_id 
WHERE
 Table1_filter.user_id IS NULL
;

有条件的总和(@juergen d答案)(所有DBMS)

SELECT 
 Table1.user_id
FROM 
 Table1
GROUP BY 
 Table1.user_id
HAVING 
 SUM(Table1.code = 9001) = 0

GROUP_CONCAT(仅适用于MySQL和SQLite)的变化(@juergen d答案)

也可以使用

... HAVING FIND_IN_SET('9001', GROUP_CONCAT(Table1.code)) = 0(仅适用于MySQL)

SELECT 
 Table1.user_id
FROM 
 Table1
GROUP BY 
  Table1.user_id
HAVING   
  GROUP_CONCAT(Table1.code) NOT LIKE '%9001%'

p.s GROUP_CONCAT(Table1.code) NOT LIKE '%9001%'还会根据所使用的数据选择误报。使用FIND_IN_SET('9001', GROUP_CONCAT(Table1.code)) = 0是更安全的选择。

参见演示http://sqlfiddle.com/#!9/fc6f6b/34