2016-12-14 42 views
1

关于连接和null有很多问题,但我无法找到与此特定模式匹配的问题。我有3个非常简单的表格。与NULL连接

+---------+ 
| service | 
+---------+ 
| id  | 
| name | 
+---------+ 

+-----------+ 
| propnames | 
+-----------+ 
| id  | 
| name  | 
| sort  | 
+-----------+ 

+----------+ 
| props | 
+----------+ 
| sid  | 
| pid  | 
| value | 
+----------+ 

我希望能够添加属性(以propnames)和查询我的服务,我的加盟性质(道具),并知道哪个属性已尚未设置。

如果是这种服务

(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 

回答

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;