1

假设我有以下表格:

+---------------------+
|   Item_Color_Meta   |
+---------------------+
| ID      |   value   |
+---------------------+
|   1     |   'red'   |
|   4     |   'blue'  |
+---------------------+

+---------------------+
|   Item_Height_Meta  |
+---------------------+
| ID      |   value   |
+---------------------+
|   1     |   '2inch' |
|   2     |   '7inch' |
|   6     |   '12inch'|
+---------------------+

我有许多这样的表,其中包含 ID 和值。我想创建一个结果集,它为所有 Id 返回一行,每个表都有一列,因此在上述情况下,结果如下所示:

ID               Color_Meta                Height_Meta
1                  'red'                     '2inch'
2                   NULL                     '7inch'
4                  'blue'                    NULL
6                   NULL                     '12inch'

我遇到的问题是加入语句,最有效的方法是什么?

4

3 回答 3

1

你需要full outer join

select
    isnull(ICM.ID, IHM.ID) as ID, ICM.Color_Meta, IHM.Height_Meta
from Item_Color_Meta as ICM
    full outer join Item_Height_Meta as IHM on IHM.ID = ICM.ID

如果你有超过 2 张桌子,你可以考虑这样

更新是的,我忘记了 MySQL 不支持full outer join,所以这个无论如何都可以工作:)

select
    A.ID, T1.Column1, T2.Column2, T3.Column3
from 
(
    select TT1.ID from Table1 as TT1 union
    select TT2.ID from Table2 as TT2 union
    select TT3.ID from Table3 as TT3
) as A
    left outer join Table1 as T1 on T1.ID = A.ID
    left outer join Table2 as T2 on T2.ID = A.ID
    left outer join Table3 as T3 on T3.ID = A.ID

这种语法很容易修改,你可以添加额外的表

检查SQL 小提琴示例

于 2012-11-24T19:35:00.040 回答
1
select  id
,       min(Color_Meta)
,       min(Height_Meta)
from    (
        select  id
        ,       value as Color_Meta
        ,       null as Height_Meta
        from    Item_Color_Meta 
        union all
        select  id
        ,       null
        ,       value
        from    Item_Height_Meta
        ) as SubQueryAlias
group by
        id

SQL Fiddle 上的实时示例。

于 2012-11-24T19:37:15.397 回答
0
    select c.id, c.val Color_Meta, h.val Height_Meta
    from Item_Color_Meta c
    left outer join Item_Height_Meta h on c.id = h.id

    UNION

    select h.id, c.val Color_Meta, h.val Height_Meta
    from Item_Height_Meta h
    left outer join Item_Color_Meta c on c.id = h.id
于 2012-11-24T20:11:27.250 回答