Mysql查询显示项目两次

时间:2015-07-16 01:33:27

标签: php mysql

过去几周我一直试图解决这个问题而且没有在哪里...... 我有两张表buy_ed和sell_ed,内容如下:

| id | item | system | station | price |

这是我的查询

$result = 
mysql_query("SELECT buy_ed.item, 
        buy_ed.price as MinPrice, 
        sell_ed.price as MaxPrice, 
        buy_ed.system as b_system, 
        buy_ed.station as b_station, 
        sell_ed.system as s_system,
        sell_ed.station as s_station, 
        (sell_ed.price - buy_ed.price) as profit  
    FROM buy_ed
    INNER JOIN sell_ed
        ON buy_ed.item=sell_ed.item
    ORDER BY profit + 0 DESC
    LIMIT 0, 50")

这是结果

--------------------------------------------------------------------------
| item1 | 100cr(system1 - station 1) | 700cr(system3 - station1) | 600cr |
| item1 | 100cr(system1 - station 1) | 400cr(system7 - station5) | 300cr |
| item2 | 700cr(system1 - station 1) | 900cr(system3 - station1) | 200cr |
| item4 | 700cr(system1 - station 1) | 850cr(system3 - station1) | 150cr |
--------------------------------------------------------------------------

如上所示,item1显示两次,以及买入价,卖出价和系统/电台名。我想要的是它只用最低的购买价格和最高的销售价格以及像这样的系统/电台名称显示一次

--------------------------------------------------------------------------
| item1 | 100cr(system1 - station 1) | 700cr(system3 - station1) | 600cr |
| item2 | 700cr(system3 - station 5) | 900cr(system2 - station1) | 200cr |
| item4 | 700cr(system9 - station 7) | 850cr(system3 - station1) | 150cr |
--------------------------------------------------------------------------

希望我能解释清楚。

1 个答案:

答案 0 :(得分:0)

行。要获得最高销售价格,您需要此查询

SELECT item, MAX(price) as MaxPrice
FROM sell_ed
GROUP BY item

同样适用于最低买入价

SELECT item, MIN(price) AS MinPrice
FROM buy_ed
GROUP BY item

所以现在我们需要在主查询中使用这些查询作为子查询来获得您想要的结果。

SELECT DISTINCT b.item, q1.MinPrice, b.system AS b_system, b.station AS b_station, q2.MaxPrice, s.system AS s_system, s.station AS s_station, (q2.MaxPrice - q1.MinPrice) AS profit
FROM buy_ed AS b INNER JOIN
(SELECT item, MIN(price) AS MinPrice
    FROM buy_ed
    GROUP BY item) AS q1
ON b.item = q1.item AND b.price = q1.MinPrice
INNER JOIN sell_ed AS s ON b.item = s.item
INNER JOIN
(SELECT item, MAX(price) as MaxPrice
    FROM sell_ed
    GROUP BY item) AS q2
ON s.item = q2.item AND s.price = q2.MaxPrice

当有2次购买或销售价格相同但系统或工作站不同时,您仍会遇到问题,这将导致重复列出的项目。