【问题标题】:Select multiple columns from a row that are based on same related table从基于同一相关表的行中选择多个列
【发布时间】:2012-05-15 04:26:45
【问题描述】:

举个例子:

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 中的引用行。谢谢!

【问题讨论】:

    标签: mysql select


    【解决方案1】:

    三个连接到不同的列就可以了:

    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

    【讨论】:

    • 我知道这是一个很大的话题,但为什么它不能扩展?上述场景只是更大、更彻底规范化的表集的一小部分。这有什么原因吗?
    • 如果您想在列表中添加第 4 种颜色怎么办?
    【解决方案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 调整其中的一些语法。

    【讨论】:

    • 选择简单地说明此处缺少的概念:表别名。
    【解决方案3】:
    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;
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-06
      • 1970-01-01
      • 1970-01-01
      • 2012-11-13
      • 2019-02-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多