Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/sharepoint/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL选择只有一些值但没有其他值的行_Mysql - Fatal编程技术网

MySQL选择只有一些值但没有其他值的行

MySQL选择只有一些值但没有其他值的行,mysql,Mysql,我有一个具有以下模式的MySQL表: | customer_id | store_id | id |-------------|----------|--- | 123 | A | 1 | 123 | B | 2 | 123 | C | 3 | 456 | A | 4 | 789 | A | 5 | 789 | C |

我有一个具有以下模式的MySQL表:

| customer_id | store_id | id
|-------------|----------|---
| 123         | A        | 1
| 123         | B        | 2
| 123         | C        | 3
| 456         | A        | 4
| 789         | A        | 5
| 789         | C        | 6
| 456         | A        | 7
比如说,我想检索所有客户id只有store id且带有A而不是B的行

所以返回的结果应该是

| customer_id | store_id | id
|-------------|----------|----
| 456         | A        | 4
| 456         | A        | 7
| 789         | A        | 5
| 789         | C        | 6
我尝试使用“不存在”,但它不起作用
选择*来自tt,其中store_id='A'且不存在选择*来自tt,其中store_id!='B'

您可以使用相关子查询:

SELECT *
FROM tt
WHERE customer_id IN (
  select customer_id
  from tt t1
  where store_id = 'A' 
  and not exists (select * from tt t2 where t1.customer_id=t2.customer_id and store_id='B'));

您可以使用相关子查询:

SELECT *
FROM tt
WHERE customer_id IN (
  select customer_id
  from tt t1
  where store_id = 'A' 
  and not exists (select * from tt t2 where t1.customer_id=t2.customer_id and store_id='B'));
如果按客户id分组并在having子句中设置条件,则可以获得所需的所有客户id:

select * from tt
where customer_id in (
  select customer_id from tt
  where store_id in ('A', 'B')
  group by customer_id
  having sum(store_id = 'B') = 0
)
看。 结果:

如果按客户id分组并在having子句中设置条件,则可以获得所需的所有客户id:

select * from tt
where customer_id in (
  select customer_id from tt
  where store_id in ('A', 'B')
  group by customer_id
  having sum(store_id = 'B') = 0
)
看。 结果:


@MadhurBhaiya对,Fixed@MadhurBhaiya对,固定