首先,我通过以下查询生成了一个表:
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。但这不是我得到的答案。
答案 0 :(得分:0)
改为使用窗口最小值:
SELECT
supplierzip
, shopzip
, MIN( type ) over(partition by supplierzip)
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
su.supplier_zip
, sp.shop_zip
) a
ORDER BY
supplierzip
, shopzip
请注意,没有理由在子查询中使用order by。
请注意,现在ONLY_FULL_GROUP_BY是MariaDB和MySQL的默认行为,坦率地说,应该一直如此(在我看来)。参见GROUP BY。
以您在问题中显示的结果为例:
+-------------+---------+-----------+
| supplierzip | shopzip | MIN(type) |
+-------------+---------+-----------+
| 7733 | 55401 | 1 |
派生自:
| 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 | <<== why is 55401 chosen???
| 7733 | 85308 | 5 |
| 7733 | 85226 | 6 |
| 7733 | 11021 | 3 |
| 7733 | 35243 | 5 |
| 7733 | 7764 | 3 |
| 7733 | 26505 | 1 |
但是没有明显的逻辑来选择shopzip55401。这(看起来像)在ONLY_FULL_GROUP_BY未打开时使用的“近似值”。