作者:159dzhqian449_734 | 来源:互联网 | 2023-10-13 10:51
这是我的餐桌动物:
╔══════════╦══════╗
║ animal ║ id ║
╠══════════╬══════╣
║ dog ║ 1 ║
║ cat ║ 4 ║
║ cat ║ 3 ║
║ bird ║ 1 ║
╚══════════╩══════╝
这是我的表名:
╔═══════╦══════╗
║ id2 ║ name ║
╠═══════╬══════╣
║ 1 ║ alan ║
║ 2 ║ bob ║
║ 3 ║ john ║
║ 4 ║ sam ║
╚═══════╩══════╝
这是我的预期结果:
╔══════════╦═════════════╗
║ dog ║ alan ║
║ cat ║ sam,john ║
║ bird ║ alan ║
╚══════════╩═════════════╝
我试过这个解决方案:
$sql = '
SELECT n.*,
x.grouped_name FROM names n
LEFT JOIN (SELECT a.id,
GROUP_CONCAT(a.animals) AS grouped_name FROM animals a GROUP BY a.id) x
ON x.id = n.id2';
foreach ($pdo->query($sql) as $row) {
echo ''.$row['animal'].' | ';
echo ''.$row['grouped_name'].' | ';
}
但我没有得到结果.
我也试过这个解决方案:
$sql = ' SELECT n.*, (SELECT GROUP_CONCAT(a.id) FROM animals a WHERE a.id = n.id2) AS grouped_name FROM names n';
但我的结果是这样的:
╔══════════╦═════════════╗
║ ║ 1,1 ║
║ ║ 3 ║
║ ║ 4 ║
╚══════════╩═════════════╝
解决方法:
SELECT t1.animal, GROUP_CONCAT(COALESCE(t2.name, "") separator ',') AS grouped_name
FROM animals t1
LEFT JOIN names t2
ON t1.id = t2.id2
GROUP BY t1.animal
看看小提琴,看动物与名字表中的任何人不匹配时的行为.为了处理这种情况,我在名称上使用COALESCE()在组连接之前用空字符串替换NULL值.
SQLFiddle