MySQL - 结合多个查询

时间:2013-04-14 05:53:14

标签: mysql sql join greatest-n-per-group

我目前有以下查询(以及一些周围的vB代码)。我希望我可以将其简化为单个SELECT语句,而不是在每个页面上再运行10个以获取个人名称。

$results = $db->query_read_slave("
    SELECT user.id AS steam, user.skills AS level
    FROM wcsp.wcgousers AS user
    WHERE race = '_wcs_' 
    ORDER BY ABS(user.skills) DESC LIMIT 10
    ");

$rank = 1;
while ($user = $db->fetch_array($results)) {
    $result = $db->query_first("
        SELECT old.name AS name
        FROM wcsp.warn_oldnames AS old
        WHERE id = '$user[steam]'
        ORDER BY lasttime
        DESC LIMIT 1
    ");

    $listing[] = array("id" => $user['steam'], "level" => $user['level'], "name" => $result['name'], "rank" => $rank);

    $rank += 1;
}

我尝试过LEFT JOIN,但我遇到的问题是我需要LEFT JOIN中的子查询类似于:

SELECT user.id AS steam, user.skills AS level, names.name AS name
FROM wcsp.wcgousers AS users
LEFT JOIN 
    (
        SELECT names.name
        FROM wcsp.warn_oldnames AS names
        WHERE id = wcsp.wcgousers.id
        ORDER BY lasttime DESC LIMIT 1
    ) AS names
ON names.id = users.id
WHERE users.race = '_wcs_'

由于子查询中的数据库检查不同,这将无效。

1 个答案:

答案 0 :(得分:1)

如果我理解正确,您希望为每个用户获取最新的Name

SELECT  a.id AS steam, 
        a.skills AS level,
        b.name
FROM    wcgousers a
        INNER JOIN warn_oldnames b
            ON a.ID = b.ID
        INNER JOIN
        (
            SELECT  ID, MAX(lasttime) max_date
            FROM    warn_oldnames
            GROUP   BY ID
        ) c ON  b.ID = c.ID AND
                b.lastTime = c.max_date
WHERE   a.race = '_wcs_'
-- ORDER  BY ABS(a.skills) DESC 
-- LIMIT  10