按组显示字段的所有示例中存在值的记录

xtfmy6hx  于 2021-06-24  发布在  Mysql
关注(0)|答案(2)|浏览(190)

我试图找出一种方法来显示表中特定字段不包含特定值的所有记录-表布局为:

id
tenant_id
request_action
request_id
request_status
hash

每个请求的\u id可以有多个操作,因此看起来像:

1    1    email    1234    1    ffffd9b00cf893297ab737243c2b921c
2    1    email    1234    0    ffffd9b00cf893297ab737243c2b921c
3    1    email    1234    0    ffffd9b00cf893297ab737243c2b921c

4    1    email    1235    1    a50ee458c9878190c24cdf218c4ac904
5    1    email    1235    1    a50ee458c9878190c24cdf218c4ac904
6    1    email    1235    1    a50ee458c9878190c24cdf218c4ac904

7    1    email    1236    1    58c2869bc4cc38acc03038c7bef14023
8    1    email    1236    2    58c2869bc4cc38acc03038c7bef14023
9    1    email    1236    2    58c2869bc4cc38acc03038c7bef14023

请求\u id可以是0(挂起)、1(已发送)或2(失败)-我要查找所有哈希,其中该哈希中的所有请求\u状态都设置为1。
在以上两个例子中 a50ee458c9878190c24cdf218c4ac904 应作为匹配项返回,因为所有请求的状态都是1,但 ffffd9b00cf893297ab737243c2b921c 不应为,虽然它包含1,但也包含一些0和 58c2869bc4cc38acc03038c7bef14023 不应该是,同样地,当它包含1时,它也包含一些2
我试过:

SELECT 
   * 
from 
  table 
where request_action='email' and request_status!=0 and request_status!=2 
group by hash

但是,这并没有给出我所需要的结果-如何仅在请求状态为1的情况下返回哈希值?

63lcw9qa

63lcw9qa1#

不知道你为什么需要 group by 在这里。你会想做一个 group by 如果你想用 GROUP_CONCAT ,或其他聚合函数( sum , max 等)
另外,不要在where子句中使用多个否定条件( request_status !=0 and request_status !=2 ),为什么不直接得到你想要的状态呢?

SELECT * FROM test WHERE request_action = 'email' AND request_status = 1

根据您的评论更新
如果不想返回任何状态为0或2的哈希值。您可以这样做:

SELECT 
    * 
FROM 
    test t
WHERE 
    request_action = 'email' AND request_status = 1 
    AND HASH NOT IN (SELECT HASH FROM test WHERE request_status IN (0, 2))

只要确保你有一个哈希索引,否则这将是非常缓慢的。

xpszyzbs

xpszyzbs2#

Create table temp select hash from your_table where 
request_status=1 group by hash

Alter table temp add index(hash)

Delete from temp where hash IN (select hash from temp 
where request_status!=1 group by hash)

Select * from your_table where hash IN(select hash from 
temp)

相关问题