我有一个包含表格的数据库:
suppliers:
fid , name
1 | 'Andrey'
2 | 'lucas'
products:
pid , name
1 | 'X'
2 | 'Y'
prdtFrn:
pid , fid , price
---------------- supplier 'andrey'
1 | 1 | 19.00
2 | 1 | 16.00
----------------- supplier 'lucas'
1 | 2 | 14.00
2 | 2 | 18.00
查询产品,我得到所有已注册的产品,但我需要知道谁以“最低价”销售“产品表”的当前产品,我不知道如何编写查询
答案 0 :(得分:3)
select p.*
from (
select pid, min(price) as MinPrice
from prdtFrn
group by pid
) pm
inner join prdtFrn p on pm.pid = p.pid and pm.MinPrice = p.price
每个产品会看到多个行,其中两个供应商以相同的价格销售产品。
答案 1 :(得分:1)
与任何复杂的SQL一样,逐步构建它。
SELECT s.name AS s_name, p.name AS p_name, sp.price
FROM suppliers AS s
JOIN prdtFrn AS sp ON s.fid = sp.fid
JOIN products AS p ON p.pid = sp.pid
这将为您提供卖家,产品和价格的清单。现在,据推测,对于每种产品,您都需要以最小价格销售产品的供应商名称的详细信息:
SELECT p_name, MIN(price) AS min_price
FROM (SELECT s.name AS s_name, p.name AS p_name, sp.price
FROM suppliers AS s
JOIN prdtFrn AS sp ON s.fid = sp.fid
JOIN products AS p ON p.pid = sp.pid
) AS spp
这为您提供每种产品的最低价格。现在,您需要将结果与第一个查询相结合,以得出答案:
SELECT spp.p_name, spp.s_name, min_price
FROM (SELECT s.name AS s_name, p.name AS p_name, sp.price
FROM suppliers AS s
JOIN prdtFrn AS sp ON s.fid = sp.fid
JOIN products AS p ON p.pid = sp.pid
) AS spp
JOIN (SELECT p_name, MIN(price) AS min_price
FROM (SELECT s.name AS s_name, p.name AS p_name, sp.price
FROM suppliers AS s
JOIN prdtFrn AS sp ON s.fid = sp.fid
JOIN products AS p ON p.pid = sp.pid
) AS spp
) AS mp
ON mp.p_name = spp.p_name AND mp.min_price = spp.price;
然后,当它工作时,您可以优化...例如,最低价格计算不需要供应商信息:
SELECT spp.p_name, spp.s_name, mp.min_price
FROM suppliers AS s
JOIN prdtFrn AS sp ON s.fid = sp.fid
JOIN (SELECT pid, MIN(price) AS min_price
FROM prdtFrn
GROUP BY pid
) AS mp
ON mp.pid = sp.pid AND mp.min_price = sp.price;
我的第一个查询出错了,因为我提供了比第一个查询中所需的更多信息;这更简单。所以,这里的课程是: