简体   繁体   English

检查列中的多个值以查找 MySQL 中的条件

[英]Checking multiple values in a column for a condition in MySQL

I have a table like:我有一张像这样的桌子:

person    product
P1        A
P1        B
P1        C
P2        A
P2        B
P2        D
P3        A

I need to write a SQL query to select person who uses product A and B, but not the product C.我需要写一个 SQL 查询给 select 使用产品 A 和 B 但不是产品 C 的人。

I tried using AND and IN operator, but it obviously shouldnt work as the result is expecting it to be.我尝试使用 AND 和 IN 运算符,但它显然不应该像预期的那样工作。

Here the expected result is:这里的预期结果是:

P2
SELECT person
FROM source_table
GROUP BY person
HAVING SUM(product = 'A')      -- at least one
   AND SUM(product = 'B')      -- at least one
   AND NOT SUM(product = 'C')  -- strictly none

Comparing result is treated as 1 when matched (is TRUE) and as 0 when not matched (is FALSE).比较结果在匹配时被视为 1(为 TRUE),在不匹配时被视为 0(为 FALSE)。 So SUMs in HAVING simply counted rows in a group which matches the condition.因此,HAVING 中的 SUM 只计算与条件匹配的组中的行。

Of course full condition form needs SUM(product = 'A') > 0 and SUM(product = 'C') = 0 .当然完整的条件形式需要SUM(product = 'A') > 0SUM(product = 'C') = 0 But MySQL treates zero as FALSe and any non-zero as TRUE, so additional compare is excess.但是 MySQL 将零视为 FALSe,将任何非零视为 TRUE,因此额外的比较是多余的。


This technique allows you to create more complex conditions.此技术允许您创建更复杂的条件。 For example:例如:

  • at least one A or B: SUM(product IN ('A', 'B'))至少一个 A 或 B: SUM(product IN ('A', 'B'))
  • at least two from the list A,B,C: SUM(product IN ('A', 'B', 'C')) >= 2列表中至少两个 A,B,C: SUM(product IN ('A', 'B', 'C')) >= 2
  • 2 or 3 from the list A,B,C,D: SUM(product IN ('A', 'B', 'C', 'D')) BETWEEN 2 AND 3列表中的 2 或 3 A,B,C,D: SUM(product IN ('A', 'B', 'C', 'D')) BETWEEN 2 AND 3

and so on...等等...

you could use something like this:你可以使用这样的东西:

SELECT person, GROUP_CONCAT(product) AS all_products
FROM mytable
GROUP BY person
HAVING all_products REGEXP ('A') 
AND all_products REGEXP ('B')
AND all_products NOT REGEXP ('C');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM