2014-01-27 81 views
2

我有以下數據也在SQL FIDDLE無法計算爲什麼子查詢返回多於一行

CREATE TABLE completework 
    (`id` int, `workerid` int, `checkerid` int); 

    CREATE TABLE worker 
    (`id` int, `name` varchar(20)); 

    INSERT INTO completework 
     (`id`, `workerid`, `checkerid`) 
    VALUES 
     (1, 2, 4), 
     (2, 3, 5), 
     (3, 4, 1), 
     (4, 5, 2), 
     (5, 1, 3), 
     (6, 2, 4), 
     (7, 3, 5), 
     (8, 4, 1), 
     (9, 5, 2), 
     (10, 1, 3), 
     (11, 2, 4), 
     (12, 3, 5), 
     (13, 4, 1), 
     (14, 5, 2); 

    INSERT INTO worker 
     (`id`, `name`) 
    VALUES 
    (1, 'Anthony'), 
    (2, 'Bill'), 
    (3, 'Claire'), 
    (4, 'Daniel'), 
    (5, 'Emma'); 

我想返回結果當操作員或者是工人或檢查,所以我想我需要工會的兩列,但是當我嘗試這樣做,我得到了錯誤

Subquery returns more than 1 row 

我曾嘗試以下

select 
    workerid as wid, 
    wn.name 
    from completework 
    inner join worker wn on completework.workerid=wn.id 
    group by wid 

以上只是得到workerid列

select 
    checkerid as cid, 
    wn.name 
    from completework 
    inner join worker wn on completework.checkerid=wn.id 
    group by cid 

以上只是得到checkerid列

SELECT DISTINCT workedonid FROM (
     SELECT checkerid workedonid FROM completework 
     UNION 
     SELECT workerid workedonid FROM completework 
    )c 
    ORDER BY workedonid ASC 

以上從任一列

select 
     (
      SELECT DISTINCT workedonid FROM (
       SELECT checkerid workedonid FROM completework 
       UNION 
       SELECT workerid workedonid FROM completework 
      )c 
     ) a, 
    wn.name 
    from completework 
    inner join worker wn on completework.checkerid=wn.id 
    group by a 

獲得一個ID在上面,我想上述工作爲子查詢,但我得到的錯誤,我該如何解決這個問題?

回答

2

試試這個:

SELECT DISTINCT w.id AS wid, w.name 
FROM worker w 
INNER JOIN completework cw ON w.id IN (cw.workerid, cw.checkerid); 

入住這SQL FIDDLE DEMO

輸出

| WID | NAME | 
|-----|---------| 
| 2 | Bill | 
| 4 | Daniel | 
| 3 | Claire | 
| 5 | Emma | 
| 1 | Anthony |