我有一个名为'employees'的数据库,其中包含以下值:
value1 | value2 | value3
-----------------------------
employee1 | key1 | boss1
employee2 | key2 | boss1
employee3 | key3 | boss1
employee4 | key4 | boss2
employee5 | key5 | boss2
在php中,我试图遍历结果以获得老板的所有员工,但只获得一次老板名称,我尝试过使用GROUP BY
,但是在循环时这只显示了第一个条目:
$query = "SELECT * FROM employees WHERE value3 = 'boss1' GROUP BY value3";
$result = $db->query($query);
$foreach ($result as $row) {
echo $row["value1"] . $row["value2"] . $row["value3"];
}
结果:
employee1 | key1 | boss1
Whitout GROUP BY
,在使用foreach
进行循环时,会为每个条目显示一次老板名称
$query = "SELECT * FROM employees WHERE value3 = 'boss1'";
$result = $db->query($query);
foreach ($result as $row) {
echo $row["value1"] . $row["value2"] . $row["value3"];
}
结果:
employee1 | key1 | boss1
employee2 | key2 | boss1
employee3 | key3 | boss1
我正试图得到一个结果:
boss1
employee1 | key1
employee2 | key2
employee3 | key3
答案 0 :(得分:1)
您可以在if()
中使用foreach
,如下所示:
foreach ($result as $row) {
$i++;
if ($i==1) {echo $row["value3"];}
echo $row["value1"] . $row["value2"];
}
比,你可以得到你想要的结果:
boss1
employee1 | key1
employee2 | key2
employee3 | key3
答案 1 :(得分:0)
您可以使用GROUP_CONCAT()
为每个comma
获取value1
({1}}和values2
的{{1}}(默认)分隔列表,如下所示:
boss
这样可以获得SELECT
GROUP_CONCAT(e.value1) AS value1,
GROUP_CONCAT(e.value2) AS value2,
e.value3 AS boss
FROM employees e
WHERE value3 = 'boss1'
GROUP BY value3;
:
boss1
编辑1:
employee1,employee2,employee3 | key1,key2,key3 | boss1
As a html list, something like: <ul>boss1 <li>employee1</li> <li>employee2</li> <li>employee3</li> </ul> I don't need the html code, but I need to get the data in a format which I can use as a list in html
注意: - 您应该使用服务器端语言来实现此目的。并使用第一个查询。