我构建了以下查询:
"{ //^"/ "/" "
这是我的数据库结构:
SELECT p.id person_id, p.name person_name, p.dob person_dob,
a.attribute, pa.value, t.type person_type
FROM people p
LEFT JOIN person_attributes pa ON pa.person_id=p.id
LEFT JOIN person_types pt ON pt.person_id=p.id
LEFT JOIN attributes a ON pa.attribute_id=a.id
LEFT JOIN types t ON pt.type_id=t.id
WHERE p.id='$person_id'
查询的结果并没有给出我预期的结果,因为它返回了一些对象而不是一个。我想选择人和所有相关数据(属性和类型)。我想我已经弄乱了那些JOINS或其他东西。我试过重新排序等等。
目前的结果是:
people(id,name,dob)
person_attributes(id,person_id,attribute_id,value)
attributes(id,attribute)
person_types(id,person_id,type)
types(id,type)
预期结果:
Array
(
[0] => stdClass Object
(
[person_id] => 2
[person_name] => Marta Smith
[person_dob] => 1995-03-16
[attribute] => size
[value] => the_value
[person_type] => type2
)
[1] => stdClass Object
(
[person_id] => 2
[person_name] => Marta Smith
[person_dob] => 1995-03-16
[attribute] => size
[value] => the_value
[person_type] => type1
)
[2] => stdClass Object
(
[person_id] => 2
[person_name] => Marta Smith
[person_dob] => 1995-03-16
[attribute] => weight
[value] => the_value
[person_type] => type2
)
[3] => stdClass Object
(
[person_id] => 2
[person_name] => Marta Smith
[person_dob] => 1995-03-16
[attribute] => weight
[value] => the_value
[person_type] => type1
)
)
是否可以对查询进行任何更改以按预期格式化?或者唯一的方法是使用PHP,循环结果并创建新对象?
答案 0 :(得分:0)
我猜这个问题出现在你的SELECT字段中。它应该是:
SELECT p.id AS person_id, p.name AS person_name, p.dob AS person_dob,
a.attribute, pa.value, t.type AS person_type
答案 1 :(得分:0)
这就是SQL的工作方式 - 你遇到的问题是SQL将为你提供一个二维扁平表结构,用于你所想要的嵌套树结构。换句话说,您的SQL结果是这样的:
2 Marta Smith 1995-03-16 size the_value type1
2 Marta Smith 1995-03-16 weight the_value type1
2 Marta Smith 1995-03-16 weight the_value type2
你需要想出一种方法来聚合/分组这些信息。您有几个选择:
LEFT JOIN