如何通过在sql中加入分组?

时间:2015-11-03 08:16:59

标签: mysql sql

我有两张桌子,让他们假装他们是以下的:

宠物

+----+----------+-------+
| 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(name)MAX(name)

所以期望的输出是:

预期输出

+----+----------+-------+-------------------+------------------+
| 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

2 个答案:

答案 0 :(得分:2)

SELECT 
    pets.id
    , pets.name
    , pets.type     
    , MIN(collars.name) as first_name
    , MAX(collars.name) as last_name 
FROM 
    pets 
LEFT OUTER JOIN 
    collars ON pets.id = collars.pet_id
GROUP BY 
    pets.id
    , pets.name
    , pets.type     

答案 1 :(得分:1)

SELECT 
    pets.id, 
    pets.name, 
    pets.type,
    MIN(collars.name) as first_name, 
    MAX(collars.name) as last_name
FROM pets LEFT JOIN collars ON pets.id = collars.pet_id
GROUP BY 
    pets.id,
    pets.name,
    pets.type