SQLite:从多个表和合并列中选择语句

时间:2014-05-11 11:19:26

标签: sqlite

我有另一种情况,我想合并一些具有相同父ID但每个组都有不同子ID的列,

这是我的table1;

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

我正在寻找一种结合列id_child

的方法

结果将是这样的:

::已编辑::

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

id_child第一行组id_boss在child_T中 第二行组id_boss在child_F

1 个答案:

答案 0 :(得分:1)

这是你想要的吗?

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 JOIN r_table AS r2
    ON r1.id_boss = r2.id_boss AND r1.id_child <> r2.id_child AND r1.answ = 'T'
;

测试here