我有两个表: 问题(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 中显示查询结果?
感谢您的帮助。
最佳答案
这可以通过两种方式解决:
仅使用 SQL:
SQL fiddle :http://www.sqlfiddle.com/#!2/19d46/14
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 列值。
关于php - 消除 MySQL 左连接查询中的重复列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16713439/