我的delas
和curencies
表格看起来像这样
curecnies
id,code
pairs (the available pairs of curencies )
id to_sell to_buy
deals
id
user_id
pair_id
amount_to_sell
amount_to_buy
所以我需要获得所有可以执行的匹配优惠,但我无法获得唯一的匹配。
这是我的SQL查询
select *
from deals as d1
join deals d2
on d1.sell_amount = d2.buy_amount and d1.buy_amount = d2.sell_amount
我得到的结果看起来像这样 id | user_id | pair_id | amount_to_buy | amount_to_sell | id | user_id | pair_id | amount_to_buy | amount_to_sell
1|2|1|1000|3000|2|1|2|3000|1000
2|1|2|3000|1000|1|2|1|1000|3000
答案 0 :(得分:0)
您可以尝试使用最少/最好的技巧:
SELECT t1.*, t2.*
FROM
(
SELECT DISTINCT
LEAST(d1.id, d2.id) AS d1_id,
GREATEST(d1.id, d2.id) AS d2_id
FROM deals AS d1
INNER JOIN deals d2
ON d1.sell_amount = d2.buy_amount AND
d1.buy_amount = d2.sell_amount
) d
INNER JOIN deals t1
ON d.d1_id = t1.id
INNER JOIN deals t2
ON d.d2_id = t2.id;
这里的基本思想是标记为d
的子查询使用最小/最大技巧找到一对匹配的交易ID。然后,我们再次加入deals
表两次,以获取该交易对中每个成员的完整信息。