循环查询多行

时间:2016-01-09 01:17:27

标签: mysql sql

我需要扫描两个表(名称匹配的所有行),然后我需要找到卖出和买入价格的最大差异。 (可以获得最高利润)

如何使用mysql严格找到此结果?我希望查询执行计算。

我有两张桌子:

SELL:

Name   | Sell_price | Seller
------------------------
Toyota | 12,000     | Mike
Toyota | 11,000     | Tony
Toyota | 9,000      | James
----------------------------
Mazda  | 5,000      | Craig
Mazda  | 4,000      | Roger
Mazda  | 3,000      | Jones

买:

Name   | Buying_Price | Buyer
------------------------
Toyota | 13,000       | Steve
Toyota | 12,000       | Andy
Toyota | 10,000       | Charles
----------------------------
Mazda  | 5,000        | Thatguy
Mazda  | 4,000        | Dog
Mazda  | 3,500        | Cat

结果:

Name   |Profit |  Buyer  | Seller
----------------------------------
Toyota | 2,000 | Charles | Mike
---------------------------------
Mazda  | 1,500 | Craig   | Cat

5 个答案:

答案 0 :(得分:2)

加入品牌表格,然后过滤以获得最高销售和最低购买价格:

select 
  sell.name, 
  sell.sell_price - buy.buying_price as profit, 
  buy.buyer, 
  sell.seller
from sell
join buy on buy.name = sell.name
where (sell.name, sell.sell_price) in
(
  select name, max(sell_price)
  from sell
  group by name
)
and (buy.name, buy.buying_price) in
(
  select name, min(buying_price)
  from buy
  group by name
);

或者反之亦然,先过滤,然后加入:

select 
  s.name, 
  s.sell_price - b.buying_price as profit, 
  b.buyer, 
  s.seller
from
(
  select *
  from sell
  where (name, sell_price) in
  (
    select name, max(sell_price)
    from sell
    group by name
  )
) s
join
(
  select * 
  from buy
  where (name, buying_price) in
  (
    select name, min(buying_price)
    from buy
    group by name
  )
) b on b.name = s.name;

答案 1 :(得分:1)

您需要将每一行与每一行进行比较,因此OUTER JOIN是您的朋友。然后,您可以在SELECT中进行计算,并使用AS分配临时列名:

SELECT s.name, (s.sell_price - b.buy_price) AS profit, s.seller, b.buyer 
FROM `sell` as s
OUTER JOIN `buy` as b ON s.name=b.name

要对其进行排序,您只需使用ORDER BY

SELECT s.name, (s.sell_price - b.buy_price) AS profit, s.seller, b.buyer 
FROM `sell` as s
OUTER JOIN `buy` as b ON s.name=b.name
ORDER BY profit

根据您的具体情况,您可能不会在代码中执行此操作。

答案 2 :(得分:1)

像(未经测试)的东西:

从卖家选择s.sell_price - b.buyer_price作为加入买家,作为b.name上的b,如b.name group by s.name,b.name;

答案 3 :(得分:1)

稍微修改一下查询,但我想它会给出更精确的结果。 如果您正在计算您的proffit作为卖家,那么您只需选择购买价格高于销售价格的行。

SELECT s.name, s.sell_price, b.buy_price, (b.buy_price - s.sell_price) AS proffit, s.seller, b.buyer 
FROM `sell` as s
RIGHT JOIN `buy` as b ON s.name=b.name WHERE b.buy_price > s.sell_price ORDER BY proffit DESC

,结果将是:

name    |  proffit   |   seller  |   buyer
--------------------------------------------
Toyota  |  4,000     |   James   |   Steve   
Mazda   |  2,000     |   Jones   |   Thatguy
Toyota  |  1,000     |   James   |   Charlie

答案 4 :(得分:0)

根据您的结果表,您只需要检索有利润而没有任何损失的记录。你可以试试这个。

SELECT s.Name, (s.Sell_Price-b.Buying_Price) AS Profit, b.Buyer, s.Seller
FROM Sell s RIGHT JOIN Buy b ON s.Name=b.Name 
WHERE b.Buying_Price > s.Sell_Price;