[英]How can I get a single value from a mysql result, if I have several rows with the same value
I have a database called 'employees' with this values: 我有一个名为“ employees”的数据库,其值如下:
value1 | value2 | value3
-----------------------------
employee1 | key1 | boss1
employee2 | key2 | boss1
employee3 | key3 | boss1
employee4 | key4 | boss2
employee5 | key5 | boss2
In php, I'm trying to loop through the result to get all the employees of a boss, but getting the boss name only once, I've tried with GROUP BY
, but when looping this only shows the first entry: 在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"];
}
Results in: 结果是:
employee1 | key1 | boss1
Whitout GROUP BY
, when looping with foreach
, it shows the boss name once for each entry 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"];
}
Results in: 结果是:
employee1 | key1 | boss1
employee2 | key2 | boss1
employee3 | key3 | boss1
I'm trying to get a result like: 我正在尝试获得如下结果:
boss1
employee1 | key1
employee2 | key2
employee3 | key3
You can use if()
in foreach
like this: 您可以在
foreach
使用if()
,如下所示:
foreach ($result as $row) {
$i++;
if ($i==1) {echo $row["value3"];}
echo $row["value1"] . $row["value2"];
}
Than, you can get the result you wanted: 比,您可以得到想要的结果:
boss1
employee1 | key1
employee2 | key2
employee3 | key3
You can use GROUP_CONCAT()
to get a comma
(default) delimited list of value1
and values2
for each boss
like this: 您可以使用
GROUP_CONCAT()
获取每个boss
的value1
和values2
的comma
分隔(默认)列表,如下所示:
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;
This will get you something like for boss1
: 这将为您提供类似于
boss1
东西:
employee1,employee2,employee3 | key1,key2,key3 | boss1
Edit 1:
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
编辑1:
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
SELECT
CONCAT('<ul>',GROUP_CONCAT(CONCAT('<li>',e.value1,'<\/li>')),'<\/ul>') AS value1,
GROUP_CONCAT(e.value2) AS value2,
e.value3 AS boss
FROM employees e
WHERE value3 = 'boss1'
GROUP BY value3;
Note :- You should use your server side language to achieve this. 注意 :-您应该使用服务器端语言来实现。 And use first query.
并使用第一个查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.