0

我对 Maria db 很陌生,但我还没有找到解决这个问题的方法。我有一个包含几个表的数据库。其中两张表是员工和客户。他们彼此没有任何关系。

create table clients (id int, name varchar(50), city varchar (20))
create table workers (id int, name varchar (50), city varchar(20))

我正在尝试编写一个选择查询,它将返回一个城市的名称、工人总数以及该城市的客户总数。clients 表有超过 2000 个条目,workers 表有 60 个。

问题是,如果我这样做:

Select workers.id, clients.id from workers, clients; 

我得到 120,000 行(60 * 2000)。我如何实现我的目标?

很抱歉,如果格式很奇怪。

4

2 回答 2

1

您可以使用union allgroup by

select city, sum(num_clients) as num_clients,
       sum(num_workers) as num_workers
from ((select city, count(*) as num_clients, 0 as num_workers
       from clients 
       group by city
      ) union all
      (select city, 0 as num_clients, count(*) as num_workers
       from workers 
       group by city
      ) 
     ) c
group by city;
于 2019-07-25T02:28:09.640 回答
0

这就是你需要的。

select
  t1.city,
  sum(t1.workers),
  sum(t1.clients)
from
  (
    select
      city,
      1 as 'workers',
      0 as 'clients'
    from
      workers
    union all
    select
      city,
      0 as 'workers',
      1 as 'clients'
    from
      clients
  ) t1
group by
  t1.city;
于 2019-07-25T02:37:54.800 回答