在三个表上使用外键进行SQL查询

时间:2014-03-12 12:22:35

标签: sql database sqlite

我有三张桌子

表1. color_sets_info set_id(PK),set_name

表2. colors set_id(FK),color_id(PK),color_namecolor_formula列< / p>

表3. mixed_colors color_id1(FK),color_id2(FK),color_formula


外键colors.set_id引用color_sets_info.set_id

外键mixed_colors.color_id1引用colors.color_id

外键mixed_colors.color_id2引用colors.color_id


如何从 mixed_colors 特定set_namecolor_formula以及所有相关列中获取:

colors.color_name(适用于mixed_colors.color_id1),

colors.color_name(适用于mixed_colors.color_id2),

color_sets_info.set_name(对于第一个colors.color_name),

color_sets_info.set_name(第二个colors.color_name

mixed_colors.color_formula


例如:

color_sets_info           colors
+--------+-----------+    +--------+----------+------------+---------------+
| set_id | set_name  |    | set_id | color_id | color_name | color_formula |
+--------+-----------+    +--------+----------+------------+---------------+
| 1      | somename1 |    | 1      | 1        | black      | R0G0B0        |
| 2      | somename2 |    | 1      | 2        | yellow     | R255G255B0    |
| 3      | somename3 |    | 2      | 3        | green      | R0G255B255    |
+--------+-----------+    | 3      | 4        | red        | R255G0B0      |
                          +--------+----------+------------+---------------+

mixed_colors
+-----------+-----------+---------------+
| color_id1 | color_id2 | color_formula |
+-----------+-----------+---------------+
| 1         | 4         | R127G0B0      |
| 2         | 3         | R127G255B127  |
| 3         | 1         | R0G127B127    |
+-----------+-----------+---------------+

我需要从 mixed_colors color_formula以及两个set_names和两个color_names获取每种混合颜色,其中1)仅使用 somename1 R127G0B0 公式 somename2 颜色设置2)

1 个答案:

答案 0 :(得分:2)

SELECT
    m.color_formula,
    cs1.set_name AS set_name1,
    c1.color_name AS color_name1,
    cs2.set_name AS set_name2,
    c2.color_name AS color_name2
FROM
    mixed_colors m
    JOIN colors c1 ON
        m.color_id1 = c1.color_id
    JOIN color_sets_info cs1 ON
        c1.set_id = cs1.set_id
    JOIN colors c2 ON
        m.color_id2 = c2.color_id
    JOIN color_sets_info cs2 ON
        c2.set_id = cs2.set_id;

或者如果您愿意,可以先将颜色和颜色集合收集到视图中:

CREATE VIEW vw_colors AS
SELECT
    color_id,
    set_id,
    color_name,
    set_name
FROM
    colors c
    JOIN color_sets_info cs ON
        c.set_id = cs.set_id;

然后查询:

SELECT
    m.color_formula,
    v1.set_name AS set_name1,
    v1.color_name AS color_name1,
    v2.set_name AS set_name2,
    v2.color_name AS color_name2
FROM
    mixed_colors m
    JOIN vw_colors v1 ON
        m.color_id1 = v1.color_id
    JOIN vw_colors v2 ON
        m.color_id2 = v2.color_id;