Mysql:按两列差异排序结果

时间:2013-12-04 10:19:36

标签: mysql

我这里有两个mysql表是我的表

table_trip

id  |  trip  |   limit

1       A        1000

2       B        2000

table_entry

id  |   tripid    |  quantity

1        1            100
2        1            100
3        2            500  
4        2            400 
5        1            200 

我想像这样显示结果

id   |  tripid  |  total_quantity   | balance(limit-total_quantity)
1         1              400                600
2         2              900                1100

并且还想显示结果order by balance 我如何使用单个查询

执行此操作

我已尝试过此查询,但无效

select a.limit,(SELECT SUM(b.quantity) FROM table_entry b where b.tripid=1) as total_quantity from table_trip a where a.id=1 order by a.limit-balance

由于

3 个答案:

答案 0 :(得分:0)

尝试这样的事情:

SELECT t.id, e.tripid, sum(e.quantity) AS total_quantity,
(t.limit - sum(e.quantity)) AS balance
FROM table_trip t LEFT JOIN table_entry e
ON t.id = e.tripid
GROUP BY t.trip
ORDER BY 3;

<强> Example..

答案 1 :(得分:0)

如果我理解你想要的东西,可能是这样的:

SELECT table_trip.id AS tripid,
entries.total_quantity,
( table_trip.limit - entries.total_quantity ) AS balance
FROM table_trip
LEFT JOIN ( SELECT tripid, SUM(quantity) AS total_quantity 
FROM table_entry GROUP BY   tripid ) AS entries ON table_trip.id=entries.tripid
ORDER BY balance ASC

答案 2 :(得分:0)

试试这个:

select a.id,b.tripid,sum(b.quantity) as total_quantity,
    a.limit-sum(b.quantity) as balance from table1 a 
    inner join table2 b on a.id=b.tripid group by a.id,b.tripid,a.limit

demo