mysql syntax error in query [closed]

让人想犯罪 __ 提交于 2021-02-05 12:29:07

问题


I'm getting an error Query failed: 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 '5,7,6,9,13 ORDER BY n.date DESC' at line 5. Can anyone point out what's wrong? Thanks

$news_query = 'SELECT u.id as userId, u.username, n.id as newsId, n.action, n.date 
            FROM newsfeed as n 
            JOIN users as u on n.userId = u.id
            WHERE
            userId in '.implode(',', array_map('intval', $myfriends)).' &&   
            userId == :myId             // posts by me
            ORDER BY n.date DESC
        ';

回答1:


The comparison operator:

 userId == :myId

In SQL the equality operator is =, not ==.

From the error message it appears that the above snippet, when the value is inserted into the query, looks like this:

userId == 5,7,6,9,13

That is not a valid comparison, even if you used the right operator. If you want to compare userId against a list of values then you should use the IN operator and a tuple (a set of values):

userId IN (5,7,6,9,13)

Response to comment

You could change your code to:

$tuple = implode(',', array_map('intval', $myfriends));
$news_query = <<< SQL
    SELECT
        u.id AS userId,
        u.username,
        n.id AS newsId,
        n.action,
        n.date 
    FROM
        newsfeed AS n 
    JOIN
        users AS u ON n.userId = u.id
    WHERE
        userId IN ($tuple) AND
        userId = :myId
    ORDER BY
        n.date DESC
SQL;

You should also qualify the userId field in the WHERE clause; i.e. put u. or n. in-front of it, so that there is no ambiguity.




回答2:


Wrap your list in parentheses here:

WHERE userId in ('.implode(',', array_map('intval', $myfriends)).') &&
                ^ here                                            ^ and here

and on the next line replace == with = (thanks to jeroen for picking this up)

userId = :myId 
       ^ here


来源:https://stackoverflow.com/questions/24275793/mysql-syntax-error-in-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!