首先,我从以下查询生成了一个表:
select su.supplier_zip, sp.shop_zip, COUNT(p.ptypes)
from supplier su
inner join parts p on su.sid=p.sid
inner join sales s on p.parts_pid=s.pid
inner join shop sp on s.shop_id=sp.shop_id
group by sp.shop_zip, su.supplier_zip
order by su.supplier_zip;
+--------------+----------+-----------------+
| supplier_zip | shop_zip | COUNT(p.ptypes) |
+--------------+----------+-----------------+
| 7733 | 85254 | 6 |
| 7733 | 33603 | 2 |
| 7733 | 92821 | 7 |
| 7733 | 95070 | 2 |
| 7733 | 94010 | 5 |
| 7733 | 68154 | 6 |
| 7733 | 45277 | 4 |
| 7733 | 94568 | 3 |
| 7733 | 55401 | 3 |
| 7733 | 85308 | 5 |
| 7733 | 85226 | 6 |
| 7733 | 11021 | 3 |
| 7733 | 35243 | 5 |
| 7733 | 7764 | 3 |
| 7733 | 26505 | 1 |
| 26505 | 85226 | 6 |
| 26505 | 55401 | 4 |
| 26505 | 92821 | 5 |
| 26505 | 45277 | 1 |
| 26505 | 26505 | 6 |
| 26505 | 94568 | 4 |
| 26505 | 85254 | 6 |
...
我正在尝试列出 COUNTS 的最小值。所以我在一个选择中做了一个选择,我最终得到:
+-------------+---------+-----------+
| supplierzip | shopzip | MIN(type) |
+-------------+---------+-----------+
| 7733 | 55401 | 1 |
| 26505 | 85308 | 1 |
| 33603 | 94568 | 3 |
| 45277 | 33603 | 1 |
| 55401 | 55401 | 1 |
| 60601 | 85254 | 3 |
| 68154 | 94568 | 2 |
| 85226 | 85226 | 6 |
| 92821 | 85226 | 5 |
| 94568 | 45277 | 2 |
+-------------+---------+-----------+
使用查询:
select supplierzip, shopzip, MIN(type)
from (
select su.supplier_zip as supplierzip, sp.shop_zip as shopzip, COUNT(p.ptypes) as type
from supplier su
inner join parts p on su.sid=p.sid
inner join sales s on p.parts_pid=s.pid
inner join shop sp on s.shop_id=sp.shop_id
group by sp.shop_zip, su.supplier_zip
order by su.supplier_zip)a
group by supplierzip;
结果是不对的。因为当您查看供应商zip-7733 时,shopzip 应该是 26505,MIN(num) 为 1。但这不是我得到的答案。