2016-12-14 77 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;