mysql - 加入没有公共(public)键的多个表

标签 mysql sql

您好,我目前有 3 个表格,如下所列。表之间没有公共(public)键

表1->linkage_Table

ID Item         Material       Color
1  keypouch     *              yellow
2  wallet       plastic        *
3  card-holder  leather        gold

表2-> Material _表

ID Name          
1  plastic
2  wool
3  leather

表3->Color_Table

ID Color
1  Yellow
2  green
3  orange

我希望得到如下结果集

Item         Material    Color

keypouch     plastic     yellow
keypouch     wool        yellow
keypouch     leather     yellow
wallet       plastic     yellow
wallet       plastic     green
wallet       plastic     orange
card-holder  leather     gold

我想写一个 SQL 语句来连接这些表。

在链接表中包含 * 意味着我们将从 Material 表或颜色表中检索所有值。

我现在真的很需要这个解决方案。试图解决这个问题超过 5 个小时。在此先感谢您的帮助。

最佳答案

一种可能的方法:

SELECT l.Item, m.name, c.Color
      FROM linkage_Table AS l
INNER JOIN Material_Table AS m
        ON l.Material = '*'
           OR l.Material = m.name
INNER JOIN Color_Table AS c
        ON l.Color = '*'
           OR l.Color = c.Color

SQL Fiddle

说明:必须构建查询,以便在相应字段中给出 '*' 时完全连接“material”和“color”表(交叉连接),或者通过这些领域的平等。这正是我们通过使用 'ON l.someField = '*' OR l.someField = joined.someField' 子句得到的结果。

关于mysql - 加入没有公共(public)键的多个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19222335/

相关文章:

C# 将数据导出到 Excel 时格式化列

mysql - ColdFusion 的 magic_quotes_gpc 设置?冷藏箱?

sql - 雪花中的地理空间连接

MySQL 连接两个表并求和?

sql - Oracle rownum 返回错误结果

mysql - Powershell管道文件内容到应用程序而不在内存中加载文件

mysql - MariaDB 10.0,innodb : Conditional Unique Constraint?

mysql - INSERT IGNORE.... SELECT.... ORDER BY... LIMIT... 在 MySql 中的确切行为是什么?

sql - 使用 BETWEEN 子句 SQL 输出缺少名称

sql - 如何为 SQL 中的每个唯一 ID 查找至少发生 3 次、持续时间至少为 15 天但不超过 90 天的观察结果?