2014-05-12 57 views
0

我還有一個情況下,我正在尋找一個查詢,可以顯示null值太大,SQLite的:SELECT語句,並顯示`null`值太大

首先在所有的,我讓表1;

+---------+----------+ 
|id_table1| value | 
+---------+----------+ 
| 1  | value1 | 
| 2  | value2 | 
| 3  | value3 | 
| 4  | value4 | 
| 5  | value5 | 
| 6  | value6 | 
| 7  | value7 | 
| 8  | value8 | 
| 9  | value9 | 
+---------+----------+ 

表2:

+---------+----------+ 
|id_table1| value | 
+---------+----------+ 
| P1 | valueP1 | 
| P2 | valueP2 | 
+---------+----------+ 

,這是我的關係表:

+---------+----------+---------+ 
|id_boss | id_child | answ | 
+---------+----------+---------+ 
| 1  |  2 | T | 
| 1  |  6 | F | 
| 2  |  P1 | T | 
| 2  |  4 | F | 
| 6  |  P2 | T | 
| 6  |  8 | F | 
+---------+----------+ --------+ 

我下面這個真棒answer,使我第一次查詢的工作,CEK這SQLFiddle

+---------+-----------+-----------+ 
|id_boss | child_T | child_F |  
+---------+-----------+-----------+ 
| value1 | value2 | value6 | 
| value2 | valueP1 | value4 | 
| value6 | valueP2 | value8 | 
+---------+-----------+-----------+ 

然後在這裏是我的新問題,

從關係表, 讓的說,我刪除一些id_child價值,所以後來我就可以填滿它,

+---------+----------+---------+ 
|id_boss | id_child | answ | 
+---------+----------+---------+ 
| 1  |  2 | T | 
| 1  |  6 | F | 
| 2  |  P1 | T | 
| 2  |  4 | F | 
| 6  |   | T | 
| 6  |   | F | 
| 4  |   | T | 
| 4  |   | F | 
+---------+----------+ --------+ 

,然後我正在尋找一種方式讓我的查詢是這樣的:

+---------+-----------+-----------+ 
|id_boss | child_T | child_F |  
+---------+-----------+-----------+ 
| value1 | value2 | value6 | 
| value2 | valueP1 | value4 | 
| value6 | `null` | `null` | 
| value4 | `null` | `null` | 
+---------+-----------+-----------+ 

回答

2

試試這個:

SELECT (SELECT value FROM table1 WHERE table1.id_table1 = r1.id_boss) AS id_boss, 
    COALESCE((SELECT value FROM table1 WHERE table1.id_table1 = r1.id_child), 
       (SELECT value FROM table2 WHERE table2.id_table2 = r1.id_child) 
      ) AS child_T, 
    COALESCE((SELECT value FROM table1 WHERE table1.id_table1 = r2.id_child), 
       (SELECT value FROM table2 WHERE table2.id_table2 = r2.id_child) 
      ) AS child_F 
FROM r_table AS r1 , r_table AS r2 
WHERE r1.id_boss = r2.id_boss AND r1.answ = 'T' AND r2.answ = 'F'; 

SQL Fiddle

它適用於我,但如果您有問題,請告訴我。

+0

是的,它的工作原理非常感謝:D – user3599629