我在名为 items_data 的表中有项目数据。
对于每一行,我有 3 列包含类别标签(cat1、cat2、cat3)。有些属于三个类别,有些只包含 1 个类别,其中 cat2 和 cat3 将有一个空单元格。
类别标签是出现在另一个名为 cat_label 的表中的 ID,该表包含两列,一列是 ID,一列是类别名称。
我想连接这两个表以形成一个新表,如果该项目属于两个类别,则会创建两行,输出将是两列,一列是项目,一列是类别。
最佳答案
使用UNION ALL
select a.item, b.name
from items_data a
join cat_label b on a.cat1 = b.id
union all
select a.item, b.name
from items_data a
join cat_label b on a.cat2 = b.id
union all
select a.item, b.name
from items_data a
join cat_label b on a.cat3 = b.id
关于sql - 使用来自多个类别的数据连接表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24279567/