我有两个表:问题(id_question,name_question,text_question)和选择(id_choice,text_choice,id_question)
我在php代码中的查询是:
$query = ' SELECT q.name_question, q.text_question, c.text_choice'.
' FROM question as q '.
' LEFT JOIN choice as c ' .
' ON q.id_question = c.id_question ' ;当我检查结果时:
foreach ($db->loadObjectList() as $obj){
echo $obj->name_question." ".$obj->text_question." ".$obj->text_choice."</br>";
}我得到的是:
Q1 Q1_text C1
Q1 Q1_text C2
Q1 Q1_text C3
Q2 Q2_text C4
Q2 Q2_text C5我想要的是:
Q1 Q1_text C1
C2
C3
Q2 Q2_text C4
C5那么,有没有办法在SQL查询中做到这一点呢?如何在PHP中以我想要的方式显示查询结果?
谢谢你的帮助。
发布于 2013-05-23 20:09:03
这可以通过两种方法来解决:
仅使用SQL:的
SQL :
SELECT case
when c.text_choice = (select min(text_choice) from choice c2 where c2.id = q.id) then name_question
else ""
end as name_question,
case
when c.text_choice = (select min(text_choice) from choice c2 where c2.id = q.id) then text_question
else ""
end as text_question,
c.text_choice
FROM question as q LEFT JOIN choice as c
ON q.id = c.id
order by q.id, c.text_choice;结果:
Q1 Q1_text C1
C2
C3
Q2 Q2_text C4
C5
C6也使用PHP:
在初次查看时,这可以通过PHP轻松完成,并按name_question对结果进行排序。
$query = ' SELECT q.name_question, q.text_question, c.text_choice'.
' FROM question as q '.
' LEFT JOIN choice as c ' .
' ON q.id_question = c.id_question ' order by q.name_question;显示结果时:
$current_nameQuestion = "";
foreach ($db->loadObjectList() as $obj){
if($current_nameQuestion==$obj->name_question)
{
echo " ".$obj->text_choice."</br>";
}
else
{
echo $obj->name_question." ".$obj->text_question." ".$obj->text_choice."</br>";
$current_nameQuestion = $obj->name_question;
}
}上面的PHP代码只会在name_question尚未输出时打印2个列值。
https://stackoverflow.com/questions/16713439
复制相似问题