mysql-通过条件使用主查询字段的子查询与子查询联接

时间:2019-02-07 12:29:12

标签: mysql

我有一个投诉表

|------------------------|
|    cid    |    desc    |
|------------------------|
|     1     |  faulty    |
|     2     |  broken    |
|     3     |  spoiled   |
|------------------------|

和分配表

|------------------------------------|
|     aid   |    cid    |    empid   |
|------------------------------------|
|     1     |     1     |     1      |
|     2     |     1     |     5      |
|     3     |     2     |     2      |
|     4     |     2     |            |
|     5     |     3     |     2      |
|     6     |     3     |     7      |
|------------------------------------|

每个投诉最多可以分配给两名员工 我需要以以下格式显示列表

|---------------------------------------------------|
|    cid    |    desc    |   emp1id   |    emp2id   |
|------------------------|--------------------------|
|     1     |  faulty    |     1      |      5      |
|     2     |  broken    |     2      |             |
|     3     |  spoiled   |     2      |      7      |
|------------------------|--------------------------|

我这样写查询

select c.cid, c.desc, a1.empid as emp1id, a2.empid as emp2id
from complaint c 
left join (
    select aid, cid, empid
    from assignment aa 
    where aa.cid = c.cid 
    limit 0,1 
) as a1 on a1.cid = c.cid
left join (
    select aid, cid, empid
    from assignment ab
    where ab.cid = c.cid
    limit 1,1
) as a2 on a2.cid = c.cid

但是它不起作用,我在子查询中遇到c.cid错误。怎么办?

1 个答案:

答案 0 :(得分:0)

这可能有用吗? (我没有安装mySql)

select  c.cid, 
        c.desc, 
        (
            select aid, cid, empid
            from assignment aa 
            where aa.cid = c.cid 
            limit 0,1 
        ) as emp1id, 
        (
            select aid, cid, empid
            from assignment ab
            where ab.cid = c.cid
            limit 1,1
        ) as emp2id
from complaint c