基于两列的MySQL返回
我有下表基于两列的MySQL返回,mysql,Mysql,我有下表 user_id | extra_id | email | status 1 | 111111 | asd@asd.com | 1 2 | 222222 | asd2@asd.com | 2 3 | 333333 | asd3@asd.com | 1 4 | 444444 | asd4@asd.com | 2 5 | 222222 | asd5@asd.com | 1 我试图返回
user_id | extra_id | email | status
1 | 111111 | asd@asd.com | 1
2 | 222222 | asd2@asd.com | 2
3 | 333333 | asd3@asd.com | 1
4 | 444444 | asd4@asd.com | 2
5 | 222222 | asd5@asd.com | 1
我试图返回状态为1(活动用户)的所有用户,但他们没有状态为2(以前已禁用)的相同额外用户id
因此,上表应该返回
user_id | extra_id | email | status
1 | 111111 | asd@asd.com | 1
3 | 333333 | asd3@asd.com | 1
如果
不存在
,您可以检查是否有另一行具有相同的额外id
和状态=2
:
select t.*
from tablename t
where t.status = 1
and not exists (
select 1 from tablename
where extra_id = t.extra_id and status = 2
)
请参阅。结果:
如果
不存在
,您可以检查是否有另一行具有相同的额外id
和状态=2
:
select t.*
from tablename t
where t.status = 1
and not exists (
select 1 from tablename
where extra_id = t.extra_id and status = 2
)
请参阅。结果:
您可以使用left-join反模式实现这一点,以确保不存在具有相同
extra\u id
和status=2
的其他记录
select t.*
from mytable t
left join mytable t1
on t1.extra_id = t.extra_id
and t1.status = 2
where
t.status = 1
t1.extra_id is null
select *
from (
select
t.*,
max(status = 2) over(partition by extra_id) has_status_2
from mytable t
) t
where status = 1 and has_status_2 = 0
或者,如果您正在运行MySQL 8.0,您可以使用窗口函数:一个窗口max()
可以告诉您相同的extra\u id
是否有另一条status=2
记录
select t.*
from mytable t
left join mytable t1
on t1.extra_id = t.extra_id
and t1.status = 2
where
t.status = 1
t1.extra_id is null
select *
from (
select
t.*,
max(status = 2) over(partition by extra_id) has_status_2
from mytable t
) t
where status = 1 and has_status_2 = 0
您可以使用left-join反模式实现这一点,以确保不存在具有相同
extra\u id
和status=2
的其他记录
select t.*
from mytable t
left join mytable t1
on t1.extra_id = t.extra_id
and t1.status = 2
where
t.status = 1
t1.extra_id is null
select *
from (
select
t.*,
max(status = 2) over(partition by extra_id) has_status_2
from mytable t
) t
where status = 1 and has_status_2 = 0
或者,如果您正在运行MySQL 8.0,您可以使用窗口函数:一个窗口max()
可以告诉您相同的extra\u id
是否有另一条status=2
记录
select t.*
from mytable t
left join mytable t1
on t1.extra_id = t.extra_id
and t1.status = 2
where
t.status = 1
t1.extra_id is null
select *
from (
select
t.*,
max(status = 2) over(partition by extra_id) has_status_2
from mytable t
) t
where status = 1 and has_status_2 = 0
StackOverflow不是免费的编码服务。你应该会的。请更新您的问题,以显示您已在某个应用程序中尝试过的内容。有关更多信息,请参阅,并选择:)进行自连接,然后从中选择。或分组依据和组concat.StackOverflow不是免费编码服务。你应该会的。请更新您的问题,以显示您已在某个应用程序中尝试过的内容。有关更多信息,请参阅,并选择:)进行自连接,然后从中选择。或分组依据和分组条件。