对两个表进行复杂查询

时间:2014-06-08 23:11:50

标签: mysql sql join

我有两张桌子:

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

哪个有多个问题:

  1. 它没有选择table2中没有条目的行
  2. 它没有正确计数
  3. ORDER BY第3部分中的组列(c1,c2)似乎存在问题。
  4. 帮助将不胜感激。


    更新

    • table1代表玩家,例如
    • table2将轮次播放,cond表示获胜
    • c1表示每位球员赢得的回合
    • c2表示由参考玩家(在这种情况下为玩家2)赢得的回合

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:1)

让我们查看查询的第一部分是否返回有效结果..

SELECT
    t1.id AS id
    COUNT(t2.id2) AS c1
    COUNT(CASE WHEN t3.id2 = 2 THEN t3.id2 ELSE NULL END) as c2
FROM
    table1 AS t1
    LEFT JOIN table2 as t2
        ON t1.id = t2.id2 AND t2.cond = 1
    LEFT JOIN table2 as t3
        ON t3.id2 = 2 AND t3.cond = 1

GROUP BY
    t2.id2,
    t3.id2

你能提供架构吗?