关于连接和null有很多问题,但我找不到与此特定模式匹配的问题。我有3个非常简单的表。
+---------+
| service |
+---------+
| id |
| name |
+---------+
+-----------+
| propnames |
+-----------+
| id |
| name |
| sort |
+-----------+
+----------+
| props |
+----------+
| sid |
| pid |
| value |
+----------+
我希望能够添加属性(到propnames)并查询我的服务,加入我的属性(props)并知道尚未设置哪些属性。
如果这是服务
(id), (name)
1, "AAA"
2, "BBB"
这是propnames
(id), (name), (sort)
1, "property_a", 1
2, "property_b", 2
3, "property_c", 3
这是道具
(service.id), (propname.id), (value)
1, 1, "Service AAA has property_a value"
1, 2, "Service AAA has property_b value"
2, 1, "Service BBB has property_a value"
然后我的查询最终会产生这个:
(service.id), (service.name), (property.id), (property.name), (props.value)
1, "AAA", 1, "property_a", "Service AAA has property_a value"
1, "AAA", 2, "property_b", "Service AAA has property_b value"
1, "AAA", 3, "property_c", NULL
2, "BBB", 1, "property_a", "Service BBB has property_a value"
2, "BBB", 2, "property_b", NULL
2, "BBB", 3, "property_c", NULL
理想情况下,它将按service.name ASC -then- property.sort
排序目前不完整的查询是:
SELECT s.id, s.name, p.id, p.name, props.value
FROM service.s
LEFT JOIN propnames p ON s.id = p.sid
LEFT JOIN props ON props.pid = p.id
ORDER BY s.name ASC, p.sort ASC
答案 0 :(得分:1)
使用cross join
生成行。然后使用left join
查找匹配项:
select s.id, s.name, p.id, p.name, props.value
from services s cross join
propnames p left join
props
on props.sid = s.id and props.pid = p.id;