从两个MySQL表中选择

时间:2017-07-18 19:52:08

标签: mysql sql

我有以下MySQL表:

tbl_pet_owners:

+----------+-------------+
| pet      | type        |
+----------+-------------+
| cat      | mammal      |
| dog      | mammal      |
| goldfish | fish        |
| goldfish | seacreature |
| snake    | reptile     |
+----------+-------------+

tbl_pet_types:

+------+----------+-------------------+
| name | pet      | type              |
+======+==========+===================+
| jane | cat      | mammal            |
+------+----------+-------------------+
| jane | dog      | mammal            |
+------+----------+-------------------+
| jack | cat      | mammal            |
+------+----------+-------------------+
| jim  | snake    | reptile           |
+------+----------+-------------------+
| jim  | goldfish | fish, seacreature |
+------+----------+-------------------+

这是我要用英语构建的SQL命令:

选择名称,宠物和宠物的类型,其中所有者的城市是波士顿。此外,结果集中不允许重复。结果将是:

SELECT result FROM (
SELECT DISTINCT owners.name, owners.pet, owners.city,
group_concat(DISTINCT types.type separator ', ') AS type
FROM tbl_pet_owners owners
INNER JOIN tbl_pet_types types ON owners.pet = types.pet
GROUP BY owners.name, owners.pet )
as result WHERE result.city = 'Boston'

这是我到目前为止所做的:

{{1}}

但我收到了错误:未知列'结果'在'字段列表'

2 个答案:

答案 0 :(得分:1)

我没有得到一个方便的mysql实例,但我认为这很接近你所需要的:

SELECT tpo.name,
       tpo.pet,
       GROUP_CONCAT(DISTINCT tpt.type separator ', ') AS type
FROM tbl_pet_owners tpo
INNER JOIN tbl_pet_types tpt ON tpt.pet = tpo.pet AND tpo.city = 'Boston'
GROUP BY tpo.name,
         tpo.pet;

编辑我把它放在SQL Fiddle

http://sqlfiddle.com/#!9/e902e/1/0

答案 1 :(得分:1)

通常有两种方法:

  1. 加入表格然后以某种方式聚合它们以便从第一个表格中获取不同的宠物并输入第二个表格。
  2. 从第一张表中获取不同的宠物,从第二张表中获取类型列表,然后加入。
  3. 我发现第二种方法要好得多,因为你只加入你想要加入的东西(带有类型列表的不同宠物)。查询是:

    select
      pet_owners.name, 
      pet_owners.pet, 
      pet_types.types
    from 
    (
      select distinct name, pet
      from tbl_pet_owners
      where city = 'Boston'
    ) pet_owners
    join
    (
      select pet, group_concat(type) as types
      from tbl_pet_types
      group by pet
    ) pet_types on pet_types.pet = pet_owners.pet;
    

    join-first-muddle-through查询看起来更简单,也可以使用:

    select 
      po.name,
      po.pet,
      group_concat(distinct pt.type) as types
    from tbl_pet_owners po
    join tbl_pet_types pt on pt.pet = po.pet
    where po.city = 'Boston'
    group by po.name, po.pet;
    

    两个表都是聚合的(一个通过DISTINCT,一个通过GROUP BY),这很好用。但是,还有其他情况,当您需要从两个表中加入聚合时,此方法失败(典型:乘以计数)。因此,在加入之前聚合是一个坚持的好习惯。