Mysql 如何在sql中进行分组连接?
我有两张桌子,让我们假设它们是: 宠物Mysql 如何在sql中进行分组连接?,mysql,sql,Mysql,Sql,我有两张桌子,让我们假设它们是: 宠物 +----+----------+-------+ | id | name | type | +----+----------+-------+ | 1 | itchy | mouse | | 2 | poochie | dog | | 3 | scratchy | cat | | 4 | john | human | +----+----------+-------+ +----+---------------
+----+----------+-------+
| id | name | type |
+----+----------+-------+
| 1 | itchy | mouse |
| 2 | poochie | dog |
| 3 | scratchy | cat |
| 4 | john | human |
+----+----------+-------+
+----+---------------+--------+
| id | name | pet_id |
+----+---------------+--------+
| 1 | collar_heaven | 2 |
| 2 | red_collar | 2 |
| 3 | cat_collar | 3 |
| 4 | tiny_collar | 1 |
| 5 | backup_collar | 2 |
+----+---------------+--------+
衣领
+----+----------+-------+
| id | name | type |
+----+----------+-------+
| 1 | itchy | mouse |
| 2 | poochie | dog |
| 3 | scratchy | cat |
| 4 | john | human |
+----+----------+-------+
+----+---------------+--------+
| id | name | pet_id |
+----+---------------+--------+
| 1 | collar_heaven | 2 |
| 2 | red_collar | 2 |
| 3 | cat_collar | 3 |
| 4 | tiny_collar | 1 |
| 5 | backup_collar | 2 |
+----+---------------+--------+
(注意宠物id#4没有项圈)
我想为与宠物连接的每个项圈选择MIN(名称)
和MAX(名称)
因此,期望的输出是:
预期产出
+----+----------+-------+-------------------+------------------+
| id | name | type | collar_first_name | collar_last_name |
+----+----------+-------+-------------------+------------------+
| 1 | itchy | mouse | tiny_collar | tiny_collar |
| 2 | poochie | dog | backup_collar | red_collar |
| 3 | scratchy | cat | cat_collar | cat_collar |
| 4 | john | human | NULL | NULL |
+----+----------+-------+-------------------+------------------+
基本上是某种
SELECT id, name, type, MIN(name) as first_name, MAX(name) as last_name
FROM pets JOIN collars
GROUP BY pet_id