我已經構建了以下查詢:複雜的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 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)
查詢是不是給了我預期的結果,因爲它的結果返回一些對象而不是一個。我想選擇人員和所有相關數據(屬性和類型)。我想我已經搞亂了那些JOINS或其他東西。我試着重新安排他們等
目前的結果是:
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,循環遍歷結果並創建新的對象?
我覺得你可以'組by'的'p.id'然後'group_concat'的'a.attribute'和't.type'。這將創建一個分隔符字符串,而不是'attributes'和'types'索引的數組。你可以爆炸它來獲得一個數組,但是你選擇的任何分隔符(確保它是唯一的)。 – chris85
@ chris85感謝您的提示。我會嘗試。 –
這是一個簡單的查詢,返回一個簡單實用的結果。不需要修改。 – Strawberry