我有三张桌子。 Foo,Attrib,FooAttrib。 FooAttrib是foo和attrib之间的桥梁。正如你所看到的,表中有许多foo和许多属性。
Foo FooAttri Attrib
------------ ----------------------------- --------------
| id | Name | | fooId | attribId | value | | id | Descrip |
|----|-------| |---------|-----------|-------| |----|---------|
| 1 | Sam | | 1 | 1 | red | | 1 | Color |
| 2 | Bill | | 1 | 2 | Grape | | 2 | Flavor |
| 3 | Ted | | 2 | 1 | Blue | | 3 | Weight |
------------ | 3 | 3 | 10 | --------------
| 1 | 3 | 5 |
| 2 | 3 | 1 |
-----------------------------
我知道如何获得以下内容:
fooId Name Attrib Value
1 Sam Color red
1 Sam Flavor Grape
1 Sam Weight 5
2 Bill Color Blue
2 Bill Weight 1
3 Ted Weight 10
但我想知道的是;是否可以构建一个select语句,以便在一个结果集中返回所有返回的foo和attrib数据,如下所示?
fooId Name Color Flavor Weight
1 Sam red Grape 5
2 Bill Blue 1
3 Ted 10
答案 0 :(得分:2)
如果您在选择时知道所需的总参数,则可以这样做:
select f.id, f.name, fa_color.value as color, , fa_flavor.value as flavor
from foo f
join fooattri fa_color on f.id = fa_color.fooid and fa_color.attribid = 1
join fooattri fa_flavor on f.id = fa_flavor.fooid and fa_flavor.attribid = 2
...
答案 1 :(得分:0)
试试这个,这种技术通常对我有用:
SELECT fo.id, fo.name,
(SELECT fooattri.value
FROM fooattri
INNER JOIN attrib ON attrib.id = fooattri.attribid
WHERE attrib.descrip = 'Color'
AND fooattri.fooid = fo.id) AS Color,
(SELECT fooattri.value
FROM fooattri
INNER JOIN attrib ON attrib.id = fooattri.attribid
WHERE attrib.descrip = 'Flavor'
AND fooattri.fooid = fo.id) AS Flavor,
(SELECT fooattri.value
FROM fooattri
INNER JOIN attrib ON attrib.id = fooattri.attribid
WHERE attrib.descrip = 'Weight'
AND fooattri.fooid = fo.id) AS Weight
FROM foo fo