一个mySQL查询来检查一个选项,如果不正确,则检查另一个选项?

时间:2019-02-28 12:10:26

标签: mysql

我在mySQL上很新。

我正在从表中查找某些记录,现在需求已更改。首先,查询将提取被标记为工作上尉的人员的姓名以及其他一些条件。现在,如果没有队长,我的老板要我把转录员拉上去。如何在MySQL中执行此操作?

我的代码是:

$Q = $this->read_db->query('
        select DISTINCT j.id, j.reference, max(ja.FinalDue) as FinalDue, j.clientdue, j.pagecount, t.name, ja.iscaptain
            from `job` j 
            join `jobattachment` a on a.`jobid` = j.`id`
            join `jobassignment` ja on a.`jobid` = ja.`jobid`
            join `transcriber` t on ja.`transcriberid` = t.`id`
            where ja.`iscaptain` = 1 
            and ja.`deleted` != 1
            and (a.`editing` = 2 or a.`editing` = 3)
            and a.`redline` != 0
            and j.`complete` = 0
            group by j.id');
    return $Q->result_array();

如何使查询查找队长,并且只有在没有队长的情况下,才能在红线字段中找到其ID的人?作业附件表为每个作业有多个记录,如果附件标记为红线,则抄录员的ID将在该字段中,否则为空。

我尝试通过添加or来更改查询,但是我不希望队长或抄写员,如果没有队长,则只希望抄写员。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

我经常玩这个游戏,这是我想出的解决方案。谢谢所有回复的人。

public function getRedlinesNotCompleted() {
    $Q = $this->read_db->query('
        select j.id, j.reference, max(ja.FinalDue) as FinalDue, j.clientdue, j.pagecount, t.name, max(ja.iscaptain) as iscaptain
            from `job` j
            join `jobattachment` a on a.`jobid` = j.`id`
            join `jobassignment` ja on a.`jobid` = ja.`jobid`
            join `transcriber` t on ja.`transcriberid` = t.`id`
            where ja.`deleted` != 1
            and (a.`editing` = 2 or a.`editing` = 3)
            and a.`redline` != 0
            and j.`complete` = 0
            group by j.id');
    return $Q->result_array();
}

public function getCaptainNameForRedlineJobsNotCompleted($jobid) {
    $Q = $this->read_db->query('
    SELECT t.name, max(j.iscaptain) as iscaptain 
    FROM jobassignment j 
    JOIN transcriber t ON t.id = j.transcriberid
    WHERE j.jobid = ' . $jobid . ' AND j.iscaptain = 1');
    return $Q->row()->name;
}

答案 1 :(得分:-1)

select DISTINCT j.id, j.reference, max(ja.FinalDue) as FinalDue, j.clientdue, j.pagecount, case when ja.iscaptain then t.name else (select name from t where id = a.redline) end , ja.iscaptain
        from `job` j 
        join `jobattachment` a on a.`jobid` = j.`id`
        join `jobassignment` ja on a.`jobid` = ja.`jobid`
        join `transcriber` t on ja.`transcriberid` = t.`id`
        where 
        and ja.`deleted` != 1
        and (a.`editing` = 2 or a.`editing` = 3)
        and a.`redline` != 0
        and j.`complete` = 0
        group by j.id'

说明: 首先从where子句中删除ja.iscaptain = 1部分,这样您就可以得到所有同样不是队长的人。

其次,t.name会根据人的不同而改变,因此,如果不是他的船长,则应检查其名字是否为t.name,而不是将其硬编码返回,否则通过a.redline id从抄录表中获取名称。

我希望我正确理解了它,对您有帮助:)