选择在同一列中的mysql查询中排除特定值的字段

问题描述 投票:0回答:3

也许声明不是很清楚,所以你走了。我们有一个mysql表,我们有这样的列:

id(key)       user_id       action
1             4832         receive_content
2             4832         click_icon
3             4832         click_image
4             4447         receive_push
5             4447         click_url  

我想写一个select语句,我们将选择user_id和动作为相同的user_id,其中action是receive_content但最终输出不包含receive_content所以输出是:

user_id           action
4832              click_icon
4832              click_image

我一直在尝试案例,但它也选择了我要排除的receive_content字段。

mysql sql database
3个回答
1
投票

您可以使用EXISTS子句检查user_id是否有receive_content动作,然后还检查每行的action不是receive_content

SELECT *
FROM actions
WHERE action != 'receive_content'
  AND EXISTS (SELECT * 
              FROM actions a2 
              WHERE action = 'receive_content' 
                AND a2.user_id = actions.user_id)

输出:

id  user_id action
2   4832    click_icon
3   4832    click_image

Demo on dbfiddle


0
投票

尝试使用内部查询:

select a.user_id, a.action
from table a
join table b on b.user_id = (select b2.user_id from table b2 where b2.action = "receive_content" and b.user_id = b2.user_id)
where a.action <> "receive_content"

0
投票

您必须在要保留的过滤器行后自己加入表,并选择所需的列。

解决方案可以是此查询:

select a.user_id,a.action 
   from actions a join actions b on a.user_id = b.user_id and a.id !=b.id 
   where 
     b.action='receive_content' and a.action != 'receive_content'     
© www.soinside.com 2019 - 2024. All rights reserved.