Mysql 从基于同一相关表的行中选择多个列

Mysql 从基于同一相关表的行中选择多个列,mysql,select,Mysql,Select,给出以下示例: fav_colors ----------------------- id col1 col2 col3 ----------------------- 01 01 03 03 02 04 02 01 03 01 03 02 colors ----------- id colors ----------- 01 green 02 red 03 blue 04 orange 对于f

给出以下示例:

fav_colors
-----------------------
id   col1   col2   col3
-----------------------
01    01     03     03
02    04     02     01
03    01     03     02

colors
-----------
id   colors
-----------
01   green
02   red
03   blue
04   orange
对于
fav_colors
表中特定ID的所有3种颜色,哪种SELECT语句可以从
colors
中提取字符串值

比如:

SELECT col1, col2, col3
FROM fav_colors
INNER JOIN ?
WHERE fc.id = 03;
我猜fav_颜色数组会使这更容易,但我依赖于这些值是独立的列。如何将同一个表连接到另一个表中的多个列

编辑:以下所有答案在技术上都有效。同意如果严重依赖多种颜色信息,最好将每种颜色记录为
fav_colors
中的参考行。谢谢

表格别名

SELECT fc.id, fc.col1, c1.colors, fc.col2, c2.colors, fc.col3, c3.colors
  FROM fav_colors AS fc
  JOIN colors AS c1 ON fc.col1 = c1.id
  JOIN colors AS c2 ON fc.col2 = c2.id
  JOIN colors AS c3 ON fc.col3 = c3.id
 WHERE fc.id = 03;
理想情况下,您会有一个
fav_colors
表,更像:

CREATE TABLE fav_colors
(
    id    INTEGER NOT NULL REFERENCES Users, -- Hypothetical table defining id values
    seq   INTEGER NOT NULL CHECK(seq BETWEEN 1 AND 3),
    color INTEGER NOT NULL REFERENCES Colors
    PRIMARY KEY(id, seq)
);

您可能需要为特定的DBMS调整一些语法。

三个不同列的连接可以实现以下目的:

SELECT c1.colors AS c1, c2.colors AS c2, c3.colors AS c3
FROM fav_colors AS fc
INNER JOIN colors AS c1 on c1.id = fc.col1
INNER JOIN colors AS c2 on c2.id = fc.col2
INNER JOIN colors AS c3 on c3.id = fc.col3
WHERE fc.id = 03; 
请记住,这是非常糟糕的表设计(根本不可伸缩)

SQLFiddle:


我将“颜色表”中的列名更改为“颜色”

我知道这是一个庞大的主题,但为什么它不能扩展?上述场景只是更大、更彻底规范化的一组表中的一小部分。这其中有什么原因吗?如果您想在列表中添加第四种颜色怎么办?选择它只是为了简单地说明此处缺少的概念:表别名。
SELECT (SELECT color FROM colors WHERE id = col1) AS color1,
(SELECT color FROM colors WHERE id = col2) AS color2,
(SELECT color FROM colors WHERE id = col3) AS color3
FROM fav_colors WHERE id = 03;