如何组合GROUP_CONCAT和LEFT JOIN?

时间:2016-06-22 05:47:01

标签: php mysql

这是我的餐桌动物:

╔══════════╦══════╗
║  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 '<td>'.$row['animal'].' </td>';
          echo '<td>'.$row['grouped_name'].' </td>'; 
     }

但我没有得到结果。

我也试过这个解决方案:

$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           ║
╚══════════╩═════════════╝

2 个答案:

答案 0 :(得分:4)

local t2 = {'foo', 'bar', 'baz'}
table.remove(t2, #t2 + 1)

当动物与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 表中的任何人不匹配时,请查看小提琴以查看行为。为了处理这种情况,我在名称上使用names在组连接之前用空字符串替换COALESCE()值。

SQLFiddle

答案 1 :(得分:1)

您可以使用这些查询

select a.animal,group_concat(n.name) as name from animals as a 
LEFT JOIN name as n ON n.id2 = a.id
group by a.animal