我正在努力解决基于特定 MySQL 查询的问题。
我有这样的结果集:
Table: Report
mammal_id mammal_name fruit_name gets | total |
3 rabbit apple 4 | 5 |
3 rabbit carrot 4 | 4 |
3 rabbit cabbage 1 | 3 |
2 squirrel nuts 1 | 3 |
2 squirrel cabbage 2 | 2 |
1 chipmunk nuts 2 | 2 |
1 chipmunk apple 1 | 1 |
And I want to filter like this:
Table: Filtered
mammal_id mammal_name fruit_name has
3 rabbit apple 4
3 rabbit carrot 4
3 rabbit cabbage 1
2 squirrel nuts 1
2 squirrel cabbage 2
1 chipmunk nuts 2
1 chipmunk apple 1
洞点是得到每只哺乳动物携带的水果的总量。
我现在有:
SELECT a.mammal_id, b.mammal_id, a.mammal_name, b.mammal_name, a.fruit_name, b.fruit_name, (b.total - a.total) as has
FROM (SELECT * FROM Report (result set)) as a
INNER JOIN (SELECT * FROM Report (result set)) as b
ON a.fruit_name=b.fruit_name WHERE a.mammal_id = b.mammal_id-1
在这个查询之后,我得到这样的结果:
Table: Result
a.mammal_id b.mammal_id a.mammal_name b.mammal_name a.fruit_name b.fruit_name has
2 3 squirrel rabbit cabbage cabbge 1
1 2 chipmunk squirrel nuts nuts 1
感谢有关此问题的任何指导。