我有两个表:

table1:
id
--
1
2
3

table2: (left out primary index)
id2 | cond
----------
3   | 1
3   | 0
2   | 1
2   | 1
2   | 0


我需要构造一个隐式计算此中间表的查询:

temp:
id | c1 | c2
------------
1  | 0  | 2
2  | 2  | 2
3  | 1  | 2


使用c1 = countRows(id2 == id && cone == 1)c2 == countRows(id2 = 2 && cond == 1)

然后选择SELECT id FROM temp ORDER BY ABS(c1 - c2)*RAND()

我目前的尝试有点像:

SELECT id, COUNT(t1.id2) AS c1, COUNT(t2.id2) AS c2
FROM table1 LEFT JOIN (table2 AS t1) ON id=t1.id2 LEFT JOIN (table2 AS t2) ON t2.id2=2
WHERE t1.cond=1 AND t2.cond=1
GROUP BY t1.id2
ORDER BY ABS(c1 - c2)*RAND()
LIMIT 1


其中有多个问题:


它不会选择table2中没有条目的行
它没有正确计数
ORDER BY第3部分中的组列(c1,c2)似乎存在问题。


帮助将不胜感激。



更新:


table1代表玩家
table2将进行回合,cond表示获胜
c1代表每个玩家赢得的回合
c2代表参考玩家(本例中为玩家2)赢得的回合

最佳答案

SELECT t1.id, SUM(IFNULL(t2.cond, 0) = 1) AS c1, (SELECT SUM(cond = 1) FROM table2 WHERE id2 = 2) AS c2
FROM table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.id2
GROUP BY t1.id
ORDER BY ABS(SUM(IFNULL(t2.cond, 0) = 1) - c2) * RAND();

10-07 13:58
查看更多