3

我整个下午都在试图处理一个查询(或两个或三个)以获得三个表的所有子项的计数。看看我的设计:

用户表

id_user | name
1 | foo
2 | bar

韩元表

id_won | user
1 | 1
2 | 1
3 | 2

绘制表格

id_draw | user
1 | 1
2 | 2
3 | 2

丢表

id_lose | user
1 | 1
2 | 1
3 | 1

我试图得到这样的东西:

name | wons | draws | loses
foo | 2 | 1 | 3
bar | 1 | 2 | 0

这是我的尝试:

select 
    u.name, w.total_w, d.total_d, l.total_l
from 
    user u
    LEFT JOIN 
    (select count(user) as total_w, user from wons group by user) as w
    ON w.user = u.id_user
    LEFT JOIN 
    (select count(user) as total_d, user from draws group by user) as d 
    ON d.user = w.user
    LEFT JOIN 
    (select count(user) as total_l, user from loses group by user) as l 
    ON d.user= .user

group by u.id_user;
4

4 回答 4

3

您可以在子查询中计算它们的总值并将它们加入到 table 中users。我添加COALESCE了显示zero而不是在其他表上不存在null的情况下。user

SELECT  a.id_user,
        COALESCE(b.totalWon,0) Wons,
        COALESCE(d.totalLoses,0) Loses,
        COALESCE(c.totalDraws,0) Draws
FROM    users a
        LEFT JOIN 
        (
            SELECT `user`, COUNT(id_won) totalWon
            FROM wons
            GROUP BY `user`
        ) b ON a.id_user = b.`user`
        LEFT JOIN
        (
            SELECT `user`, COUNT(id_draw) totalDraws
            FROM draws
            GROUP BY `user`
        ) c ON a.id_user = c.`user`
        LEFT JOIN
        (
            SELECT `user`, COUNT(id_lose) totalLoses
            FROM loses
            GROUP BY `user`
        ) d ON a.id_user = d.`user`

SQLFiddle 演示

于 2012-09-29T01:28:22.823 回答
2
select u.name, w.uw as wins, l.ul as loses, d.ud as draws from user
    left join (select user, COUNT(id_won) uw from wons group by user) w on w.user = u.user_id
    left join (select user, COUNT(id_lose) ul from loses group by user) l on l.user = u.user_id
    left join (select user, COUNT(id_draw) ud from draws group by user) d on d.user = u.user_id

这只是任务所需的工作量。

于 2012-09-29T01:31:01.420 回答
2

最干净的 SQL 是:

SELECT 
    u.name,
    w.wins,
    d.draws,
    l.loses
FROM
    user u
LEFT JOIN 
    (SELECT user,COUNT(*) wins FROM wons GROUP BY user) w ON w.user = u.id_user
LEFT JOIN 
    (SELECT user,COUNT(*) draws FROM draws GROUP BY user) d ON d.user = u.id_user
LEFT JOIN 
    (SELECT user,COUNT(*) loses FROM loses GROUP BY user) l ON l.user = u.id_user

http://sqlfiddle.com/#!2/91b61/10

于 2012-09-29T01:45:13.790 回答
0

我会建议一种替代方法,这可能对您的项目来说是一种过度杀伤,但如果您要大量生成所需的结果,请牢记性能。

创建一个汇总表(类似于您想要的输出)。您可以在那里清空为每个用户创建的 shell 记录。

在赢、平和输表中添加触发器,简单地更新汇总表中的数据。

这是一种方法。下一种方法是,如果您想要的结果不是关键任务(即不必是最新的东西),那么考虑添加一个计划的事件(每 10 或 20 分钟运行一次,运行上面提供的查询(我已经给 +1 票)并使用它来更新汇总表。

祝你好运!

于 2012-09-29T01:40:03.507 回答