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

时间:2012-05-15 04:26:45

标签: 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

什么类型的SELECT语句用于从colors中为fav_colors表中的特定ID的所有3种颜色提取字符串值?

类似的东西:

SELECT col1, col2, col3
FROM fav_colors
INNER JOIN ?
WHERE fc.id = 03;

我猜一个fav_color数组会让这更容易,但依赖于这些值是单独的列。如何将同一个表连接到另一个表中的多个列?

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

3 个答案:

答案 0 :(得分:4)

不同列的三个连接可以解决问题:

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:http://sqlfiddle.com/#!2/5b01b/6

答案 1 :(得分:2)

表别名......

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调整一些语法。

答案 2 :(得分:1)

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;

我在列表中将列名更改为颜色