MySQL的 - 与在使用主查询的字段条件与子查询子连接的查询

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

我要投诉表

|------------------------|
|    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      |
|------------------------------------|

每一个投诉可以被分配到atmost两名员工我需要显示在下面的格式列表

|---------------------------------------------------|
|    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收到错误。怎么做?

mysql
1个回答
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 
© www.soinside.com 2019 - 2024. All rights reserved.