Mysql 复杂sql查询未给出预期结果
我构造了以下查询:Mysql 复杂sql查询未给出预期结果,mysql,sql,Mysql,Sql,我构造了以下查询: 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 perso
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'
以下是我的数据库结构:
people(id,name,dob)
person_attributes(id,person_id,attribute_id,value)
attributes(id,attribute)
person_types(id,person_id,type)
types(id,type)
查询的结果没有给我预期的结果,因为它返回的是几个对象,而不是一个。我想选择person和所有相关数据(属性和类型)。我想我把那些连接搞砸了。我试着重新排列它们等等
目前的结果是:
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
)
)
预期结果:
[0] => stdClass Object
(
[person_id] => 2
[person_name] => Marta Smith
[person_dob] => 1995-03-16
[attributes] => // array of all attributes with values here
[types] => // array of all person types here
)
是否可以对查询进行任何更改以按预期设置其格式?或者唯一的方法是使用PHP,循环结果并创建新对象?我想问题出在选择字段部分。应该是:
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
我想问题出在你的选择字段部分。应该是:
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
这就是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
您需要想出一种方法来聚合/分组这些信息。您有几个选择:
左连接
这就是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
您需要想出一种方法来聚合/分组这些信息。您有几个选择:
左连接
我想你可以按
p.id
分组a.attribute
和t.type
。这将生成一个分隔符字符串,而不是属性
和类型
索引的数组。你可以将它分解得到一个数组,但不管你选择什么分隔符(确保它是唯一的)。@chris85谢谢你的提示。这是一个简单的查询,返回一个简单实用的结果。无需修改。我认为您可以按p.id
分组a.attribute
和t.type
。这将生成一个分隔符字符串,而不是属性
和类型
索引的数组。你可以将它分解得到一个数组,但不管你选择什么分隔符(确保它是唯一的)。@chris85谢谢你的提示。这是一个简单的查询,返回一个简单实用的结果。无需修改。