我有三张桌子
表1. color_sets_info
与set_id
(PK),set_name
列
表2. colors
与set_id
(FK),color_id
(PK),color_name
,color_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_name
或color_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)
答案 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;