1

我有一个对象表、一个定义属性的表和一个包含对象属性值的表:

OBJECTS:
ID  | ...
----+-----
1   | ...
2   | ...

ATTRIBUTES:
KEY  | DEFAULT
-----+---------
a1   | xyz
a2   | abc
a3   | 123

OBJECT_ATTRIBUTES:
OBJECT_ID  | KEY  | VALUE 
-----------+------+-------
1          | a1   | abcd
1          | a2   | xyzw
2          | a3   | 12345

所以每个对象都可以为其属性定义值,否则default应该使用 for 该属性。

现在我需要一个选择来连接所有具有所有属性的对象,替换default任何时候OBJECT_ATTRIBUTES记录不存在:

INTENDED QUERY RESULT:
OBJECT_ID  | ...  | KEY  | VALUE 
-----------+------+------+-------
1          | ...  | a1   | abcd
1          |      | a2   | xyzw
1          |      | a3   | 123 <- filled in default
2          |      | a1   | xyz <- filled in default
2          |      | a2   | abc <- filled in default
2          |      | a3   | 12345

我怎样才能在 SQL 中做到这一点?


在首屏:现在我只选择

SELECT * FROM OBJECT LEFT JOIN OBJECTS_ATTRIBUTES ON ID = OBJECT_ID

但后来我必须手动填写空白。

4

2 回答 2

3

您需要获取 table 的笛卡尔积,Objects因此Attributes所有对象都包含所有属性。

SELECT  a.*,
        b.key,
        COALESCE(c.value, b.default) Value
FROM    Objects a
        CROSS JOIN Attributes b
        LEFT JOIN Object_Attributes c
            ON  a.ID = c.object_id AND
                b.key = c.key
ORDER   BY a.ID, b.key
于 2013-10-10T07:28:49.937 回答
1

您可以从和中获取所有现有条目OBJECT_ATTRIBUTES,然后添加(UNION ALL)缺少的组合:OBJECTSATTRIBUTES

SELECT OBJECT_ID, KEY, VALUE
FROM OBJECT_ATTRIBUTES

UNION ALL

SELECT o.ID, a.KEY, a.DEFAULT
FROM OBJECTS AS o
CROSS JOIN ATTRIBUTES AS a
WHERE NOT EXISTS (
  SELECT *
  FROM OBJECT_ATTRIBUTES
  WHERE OBJECT_ID = o.ID AND KEY = a.KEY
);
于 2013-10-11T07:02:21.007 回答