内部联接数据库查询?

时间:2018-07-08 17:02:37

标签: sql database

我有2个表,items_tableitem_bidding_table

items_table具有以下列:

id, name, desc, quantity, unit_price 

item_bidding_table有这些列

id, item_id(FK), amount 

其中item_iditem_bidding_table的外键。

在以下情况下,我需要查询以返回items_table(所有列)的完整行:

    amount中的
  1. item_bidding_table值必须大于unit_price中的items_table

  2. 返回的unit_price值必须是item_bidding_table

  3. 中的最大值

示例:

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中最大的金额。

那么返回此输出所需的查询是什么?

4 个答案:

答案 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后,您将获得每个订单的最高出价。最后,需要joinwhere子句才能满足您的条件。

答案 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()无关紧要,但是只要有联接,就先进行聚合,然后联接。