0

给定以下示例:

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

colors什么样的 SELECT 语句可以从表中特定 ID 的所有 3 种颜色中提取字符串值fav_colors

就像是:

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

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

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

4

3 回答 3

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

于 2012-05-15T04:32:20.297 回答
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 调整其中的一些语法。

于 2012-05-15T04:31:48.133 回答
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;

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

于 2012-05-15T04:46:59.333 回答