加入没有中心密钥源表的列

时间:2012-11-24 19:31:59

标签: mysql sql

说我有以下表格:

+---------------------+
|   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'

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

3 个答案:

答案 0 :(得分: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

如果你有两张以上的桌子,你可以考虑这样的事情

更新是的,我忘记了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 FIDDLE EXAMPLE

答案 1 :(得分: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

Live example at SQL Fiddle.

答案 2 :(得分: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