mysql子查询返回错误

时间:2012-03-01 15:51:59

标签: php mysql sql join subquery

SELECT 
    upd.*,
    usr.username AS `username`,
    usr.profile_picture AS `profile_picture`
    ,(
        SELECT COUNT (like.id)
        FROM likes as like
        WHERE upd.update_id = like.item_id
           AND like.uid = 118697835834
    ) as liked_update

FROM updates AS upd
LEFT JOIN users AS usr 
    ON upd.uid = usr.uid
WHERE upd.deleted=0
    AND 
    ( upd.uid=118697835834
        OR EXISTS ( SELECT *
                    FROM   subscribers AS sub 
                    WHERE  upd.uid = sub.suid
                    AND  sub.uid = 118697835834
            )
    )
ORDER BY upd.date DESC
LIMIT 0, 15

SELECT中的子查询返回以下错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL 
    server version for the right syntax to use near 
    'like WHERE upd.update_id = like.item_id AND l' at line 10

4 个答案:

答案 0 :(得分:6)

like是SQL中的保留字;您应该为likes表使用不同的别名。从以下位置更改子查询:

SELECT
    COUNT (like.id)
FROM
    likes as like
WHERE
    upd.update_id = like.item_id
    AND like.uid = 118697835834

类似于:

SELECT
    COUNT (l.id)
FROM
    likes as l
WHERE
    upd.update_id = l.item_id
    AND l.uid = 118697835834

答案 1 :(得分:1)

就像是一个保留的SQL词

将您的别名更改为已删除或喜欢的信息,您的请求应该有效。

答案 2 :(得分:1)

您不能将Like用作别名,而是保留字

SELECT 
    upd.*,
    usr.username AS `username`,
    usr.profile_picture AS `profile_picture`
    ,(
        SELECT COUNT (l.id)
        FROM likes as l
        WHERE upd.update_id = l.item_id
           AND l.uid = 118697835834
    ) as liked_update

FROM updates AS upd
LEFT JOIN users AS usr 
    ON upd.uid = usr.uid
WHERE upd.deleted=0
    AND 
    ( upd.uid=118697835834
        OR EXISTS ( SELECT *
                    FROM   subscribers AS sub 
                    WHERE  upd.uid = sub.suid
                    AND  sub.uid = 118697835834
            )
    )
ORDER BY upd.date DESC
LIMIT 0, 15

答案 3 :(得分:0)

尽量不要在表字段名称或任何其他变量中使用“like”,因为它是一个SQL关键字 - 与SELECT或AND相同。