0

我正在尝试SELECT在三个关系表上创建一个,如下所示:

table_materials
-> material_id
- material_name

table_props
-> prop_id
- prop_name

table_materials_props
- row_id
-> material_id
-> prop_id
- prop_value

在我的页面上,我想得到这样的结果,但我的查询有一些问题:

material    prop A    prop B    prop C    prop D    prop E
wood        350       NULL      NULL      84        16
iron        NULL      17        NULL      NULL      201
copper      548       285       99        NULL      NULL

所以查询应该返回如下内容:

material   prop_name     prop_value
wood       prop A        350
wood       prop B        NULL
wood       prop C        NULL
wood       prop D        84
wood       prop E        16
// and go on with others rows

我想使用类似的东西:

SELECT *
FROM table_materials AS m
INNER JOIN table_materials_props AS mp
ON m.material_id = mp.material_id
INNER JOIN table_materials_props AS p
ON mp.prop_id = p.prop_id
ORDER BY p.prop_name

问题是查询不返回NULL值,我需要相同的prop顺序来处理所有materials道具值NULL or not

我希望这个例子很清楚!

4

1 回答 1

0

交叉连接(或内部连接 ​​w/oa 条件)所有选项,然后将这些选项左连接到关联实体表。即使组合不存在于关联表中,左连接也会保留道具/材料。

未经测试:

SELECT * 
FROM table_materials AS m
INNER JOIN table_props as p 
LEFT JOIN table_material_props AS mp 
ON p.prop_id = mp.prop_id 
AND 
m.material_id = mp.material_id;
ORDER BY p.prop_name
于 2010-04-29T18:22:53.067 回答