【问题标题】:how to get mysql values based on left join condition如何根据左连接条件获取mysql值
【发布时间】:2020-03-09 09:50:48
【问题描述】:

工作表

1.id
2.status = 'active'
3.name

修表

1.repair id
2.job_id
3.process = 'yes|no'
4.status  = '1|2'

工作表

id   name  status
1    test  active
2    check active

修表

repair_id     job_id  process  status
1                1      no        2
2                1      no        1
3                1      yes       2
4                2      no        1
5                2      no        2

这里我需要显示按 job_id 分组的数据(process != 'yes' and repair_status != 2)

我需要查询后的结果

---------------------------------------------
job_id    name( job.name ) status( job.status )
------------------------------------------------
2            check           active

【问题讨论】:

标签: mysql sql subquery left-join having-clause


【解决方案1】:

为了获得您指定的结果,您的意思是process 不是yes任何job_id。然后至少一行有一个status 2。那就是:

select j.job_id, j.name, j.status
from repair r join
     job j
     on r.job_id = r.id
group by j.job_id, j.name, j.status
having max(process) = 'no' and
       min(repair_status) = 1;

【讨论】:

    【解决方案2】:

    如果您想要使用process = 'yes'status = 2 修复不存在的作业,您可以使用not exists

    select j.*
    from jobs j
    where not exists (
        select 1 
        from repair r 
        where r.job_id = j.id and r.process = 'yes' and r.status = 2
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-25
      • 2019-08-08
      • 2015-08-21
      • 2021-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多