我有一个产品,供应商和prdtFrn表,如下所示:
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
我正在寻找一个SQL查询,它将 返回以低于 我的价格出售的所有产品(andrey)。在这个例子中,我想获得产品“X”,因为卢卡斯以低于我的价格出售它。
答案 0 :(得分:2)
许多其他答案似乎很复杂,但答案很简单:
select distinct p1.*
from prdtfrn p1
join prdtfrn p2 on p1.pid = p2.pid and p2.fid != 1 and p2.price < p1.price
where p1.fid = 1; // fid=1 is known to be 'Audrey'
此查询列出了其他地方销售更便宜的所有产品。
答案 1 :(得分:1)
只需从prdtFrn
表中选择两次。从那里,查询很简单。
我在下面列出了一个未经测试的示例。 A
对应于竞争对手的产品,B
对应于您的产品。
SELECT
suppliers.name,
A.pid,
A.price
FROM
prdtfrn AS A,
prdtfrn AS B,
suppliers
WHERE
A.price < B.price
AND A.pid = B.pid
AND B.fid = 1
AND A.fid = suppliers.fid;
答案 2 :(得分:1)
我认为您正在与许多供应商( 不仅仅是lucas )进行比较,所以这是我的查询。试试这个:
SELECT e.name,
g.name,
f.price
FROM suppliers e INNER JOIN prdtFrn f ON
e.fid = f.fid
INNER JOIN products g ON
f.pid = g.pid
WHERE e.name <> 'Andrey' AND -- this selects all products which is not yours
f.pid IN -- the selected products should match your products
(SELECT c.pid -- this subquery selects all your products
c.name,
b.price
FROM suppliers a INNER JOIN prdtFrn b ON
a.fid = b.fid
INNER JOIN products c ON
b.pid = c.pid
WHERE a.name = 'Audrey') d AND
f.price < d.price -- product is less than yours
答案 3 :(得分:1)
这是一个获取您正在寻找的信息的查询。由于可能有其他供应商出售的产品而您没有,我认为您可能也有兴趣找到它们。
这是您要求的查询(没有其他供应商提供的产品,您没有):
select sp2.pid, p.name as ProductName, sp2.price, s2.name as SupplierName
from prdtFrn sp2 join (
select sp.pid, sp.price from suppliers s
join prdtFrn sp on sp.fid = s.fid
where s.name = 'Andrey'
) as AndreysProducts
on AndreysProducts.pid = sp2.pid
join products p on sp2.pid = p.pid
join suppliers s2 on s2.fid = sp2.fid
where sp2.price < AndreysProducts.price
这是您可能感兴趣的查询(使用其他供应商提供的产品,但您没有):
select sp2.pid, p.name as ProductName, sp2.price, s2.name as SupplierName
from prdtFrn sp2 left join (
select sp.pid, sp.price from suppliers s
join prdtFrn sp on sp.fid = s.fid
where s.name = 'Andrey'
) as AndreysProducts
on AndreysProducts.pid = sp2.pid
join products p on sp2.pid = p.pid
join suppliers s2 on s2.fid = sp2.fid
where sp2.price < AndreysProducts.price or AndreysProducts.pid is null