我有2个表,items_table
和item_bidding_table
。
items_table
具有以下列:
id, name, desc, quantity, unit_price
而item_bidding_table
有这些列
id, item_id(FK), amount
其中item_id
是item_bidding_table
的外键。
在以下情况下,我需要查询以返回items_table
(所有列)的完整行:
amount
中的 item_bidding_table
值必须大于unit_price
中的items_table
返回的unit_price
值必须是item_bidding_table
示例:
items_table
:
[id | name | desc | quantity | unit_price ]
[1 | rice | food | 5 | 10 ]
[2 | Eggs | food | 6 | 15 ]
item_bidding_table
:
[id | item_id | amount ]
[1 | 1 | 9 ]
[2 | 1 | 12 ]
预期输出:
[1 | rice | food | 5 | 12 ]
其中 12 是item_bidding_table
中最大的金额。
那么返回此输出所需的查询是什么?
答案 0 :(得分:2)
您可以使用以下查询获得所需的结果。
select
i.id, i.name, i.desc, i.quantity,
max(ib.amount)
from
items_table i
inner join
item_bidding_table ib on i.id = ib.item_id
where
ib.amount > i.unit_price
group by
i.id, i.name, i.desc, i.quantity
提示:每当需要使用聚合函数(例如(最小,最大,平均)等)时,请考虑group by子句,并尝试朝该方向构建查询。
答案 1 :(得分:0)
尝试此查询:
SELECT * FROM
(
SELECT *
FROM item_bidding_table
ORDER BY amount DESC
) t
JOIN items_table t ON t.id = b.item_id
WHERE t.unit_price <= b.amount
GROUP BY t.id
子查询按降序对出价进行排序。添加group by
后,您将获得每个订单的最高出价。最后,需要join
和where
子句才能满足您的条件。
答案 2 :(得分:0)
Try this :
select a.*, b.amt as amount from items_table a
cross apply (select max(amount) as amt from item_bidding_table where item_id = a.id group by item_id) b
答案 3 :(得分:-1)
这几乎可以在所有SQL后端中使用并且效率很高(也不取决于items_table id是唯一的-您并未真正说出是否存在):
select name , desc , quantity, amount
from items_table i
inner join
(select item_id, max(amount) as amount
from item_bidding_table
where amount > unit_price
group by item_id) tmp on i.id = tmp.item_id
注意:此查询中的Max()无关紧要,但是只要有联接,就先进行聚合,然后联接。