PHP使用左连接时如何按结果数组分组
为了简化对我的问题的解释,假设我做了一个小sql查询,从三个表中选择数据:PHP使用左连接时如何按结果数组分组,php,mysql,group-by,Php,Mysql,Group By,为了简化对我的问题的解释,假设我做了一个小sql查询,从三个表中选择数据: SELECT blockTitre, ChampsType, ChampsNom FROM form_builder LEFT JOIN block_champs ON formBuilderBId = blockId RIGHT JOIN ajout_champs ON ChampsId = formBuilderChId 当我对结果进行var_转储时,我得到以下结果
SELECT blockTitre, ChampsType, ChampsNom
FROM form_builder
LEFT JOIN block_champs
ON formBuilderBId = blockId
RIGHT JOIN ajout_champs
ON ChampsId = formBuilderChId
当我对结果进行var_转储时,我得到以下结果:
array (size=6)
0 =>
object(stdClass)[8]
public 'blockTitre' => string 'Misc' (length=4)
public 'ChampsType' => string 'submit' (length=6)
public 'ChampsNom' => string 'submit' (length=6)
1 =>
object(stdClass)[9]
public 'blockTitre' => string 'Misc' (length=4)
public 'ChampsType' => string 'hidden' (length=6)
public 'ChampsNom' => string 'page' (length=4)
2 =>
object(stdClass)[10]
public 'blockTitre' => string 'Information général' (length=21)
public 'ChampsType' => string 'text' (length=4)
public 'ChampsNom' => string 'email' (length=5)
3 =>
object(stdClass)[11]
public 'blockTitre' => string 'Information général' (length=21)
public 'ChampsType' => string 'text' (length=4)
public 'ChampsNom' => string 'prenom' (length=6)
4 =>
object(stdClass)[12]
public 'blockTitre' => string 'Information général' (length=21)
public 'ChampsType' => string 'text' (length=4)
public 'ChampsNom' => string 'age' (length=3)
5 =>
object(stdClass)[13]
public 'blockTitre' => string 'Misc' (length=4)
public 'ChampsType' => string 'text' (length=4)
public 'ChampsNom' => string 'nommm' (length=5)
我想要的是通过blockTitre重新组合结果
我尝试了SQL语句groupby
,但它只返回两行(我认为这是逻辑)
请掌握如何将所有行按blockTitre分组
先谢谢你
编辑:
请告诉我,我需要像这样的东西:
0 =>
'blockTitre' => string 'Misc'
'ChampsType' => string 'submit'
'ChampsNom' => string 'submit'
'ChampsType' => string 'text'
'ChampsNom' => string 'nommm'
'ChampsType' => string 'hidden'
'ChampsNom' => string 'page'
1 =>
'blockTitre' => string 'Information général'
'ChampsType' => string 'text'
'ChampsNom' => string 'email'
'ChampsType' => string 'text'
'ChampsNom' => string 'prenom'
'ChampsType' => string 'text'
'ChampsNom' => string 'age'
GROUP BY
在描述您的情况时起作用。它将只留下唯一的值:Misc
和Information général
。它将使用它看到的第一行作为其他列的值。因此,实际上,您将只获得2行
您想要的输出是什么?通常使用groupby
只获取唯一值,或者进行某种计数
请记住,SQL只能为您提供“平面”数据,即以下结构:
data = {
"misc": [{
"row1",
"row2"
}],
"info": [{
"row1",
"row2"
}]
}
如果您使用PDO,则必须逐行读取结果集。请查看PDO::FETCH_GROUP
要获取按blockTitre
分组的结果,请尝试以下操作(假设您已经使用PDO执行了查询):
可以找到更多信息
现在,您可以按自己的喜好在组中循环。只要确保
GROUP BY blockTitre
在您的查询中。是的,但我不想只获取它看到的第一行,我需要全部主题。可以吗?如果您想要所有行,请不要使用分组依据
。为什么要使用“分组依据”
?您希望结果集看起来像什么?是的,这正是MySQL不能为您做的。省去groupby
,自己用PHP做分组逻辑。+1非常感谢您向我解释这一点。你有什么办法用php来做吗?我无法想象怎么做?我正在使用MySQLi。请问等价物是什么?只是快速浏览了一下文档,在MySQLi中似乎没有等价物。您可以从$res->fetchAll()
循环遍历结果集,并自己分组。
GROUP BY blockTitre