SQL加入MAX()。

时间:2014-04-02 04:40:49

标签: mysql sql inner-join

我有两张桌子,用户和参赛者。我试图选择具有个人资料照片的最大参赛者ID(位于用户桌面上)

这是我可怕的SQL:

SELECT u.thumbnail, u.id FROM users AS u
INNER JOIN
(
 SELECT c.id, c.user_id FROM contestants AS c
 WHERE u.id = c.users_id
AND c.id = (select max(c.id))
) WHERE u.thumbnail IS NOT NULL

目前的错误是:#1248 - 每个派生表都必须有自己的别名。

这让我感到困惑,因为用户的别名为u,参赛者的别名是c ..

我在这里做错了什么?我猜了很多,所以一些帮助会非常感激!

4 个答案:

答案 0 :(得分:3)

每当您执行连接操作时,您实际上正在加入两个表。例如,您在此处编写的子查询作为单独的表工作。因此,您必须使用此表的别名。这就是您的错误消息背后的原因。

您的查询:

    SELECT u.thumbnail, u.id FROM users AS u
    INNER JOIN
    (
    SELECT c.id, c.user_id FROM contestants AS c
    WHERE u.id = c.users_id
    AND c.id = (select max(c.id))
    ) WHERE u.thumbnail IS NOT NULL

它应该包含子查询的别名:

    SELECT c.id, c.user_id FROM contestants AS c
    WHERE u.id = c.users_id
    AND c.id = (select max(c.id))

让我们说,它是T。

因此,您的查询现在变为:

    SELECT u.thumbnail, u.id FROM users AS u
    INNER JOIN
    (
    SELECT c.id, c.user_id FROM contestants AS c
    WHERE u.id = c.users_id
    AND c.id = (select max(c.id)) 
    ) AS T
    WHERE u.thumbnail IS NOT NULL

但是你想要实现的目标实际上可以用一种更简洁的方式来实现:

    SELECT u.thumbnail, u.id, max(c.id),
    FROM users as u
    LEFT JOIN contestants as c
    on u.id = c.user_id
    WHERE u.thumbnail IS NOT NULL

为什么在你有更好更整洁的方法时会大惊小怪呢?

答案 1 :(得分:2)

试试这个:

SELECT u.thumbnail, u.id 
FROM users AS u
INNER JOIN
(
 SELECT c.id, c.user_id FROM contestants AS c
 WHERE u.id = c.users_id
 AND c.id = (select max(c.id))
)A 
WHERE u.thumbnail IS NOT NULL

答案 2 :(得分:0)

我认为这应该很简单,

SELECT  u.thumbnail, u.id
FROM    users u
        INNER JOIN contestants c
            ON u.id = c.users_id
WHERE   u.thumbnail IS NOT NULL
ORDER   BY c.id DESC
LIMIT   1

答案 3 :(得分:0)

这很简单。

SELECT  user.thumbnail, user.id
FROM    users user
        INNER JOIN contestants cont ON cont.id = cont.users_id
WHERE   cont.thumbnail IS NOT NULL
ORDER   BY user.id DESC