MySQL子句中的数组问题

[英]MySQL IN Clause with Array issue


My IN clause works in the first query but not in the 2nd. The larger query works just fine without the IN clause so there are no issues there. Looked through docs but couldn't see where I am going wrong.

我的IN子句在第一个查询中有效,但在第二个查询中无效。较大的查询在没有IN子句的情况下运行良好,因此不存在问题。看了看医生,但看不出我哪里出错了。

Works:

工作原理:

'SELECT email, first_name, last_name 
    FROM users 
WHERE user_id 
    IN (' . implode(',', array_map('intval',$userData)) . ')'

Does not work:

不工作:

'SELECT
    u.user_id, u.email, u.first_name, u.last_name, a.job_id, a.user_id, ap.job_id, ap.app_id, ap.location, p.user_id, p.filename, p.selected, g.street, g.city, g.state
FROM users u
    JOIN applications ap ON ap.user_id = u.user_id
    JOIN applicants a ON a.user_id = a.user_id AND a.app_id = ap.app_id AND ap.job_id = a.job_id
    LEFT OUTER JOIN user_photos p ON u.user_id = p.user_id AND p.selected = 1
    LEFT OUTER JOIN user_general g ON u.user_id = g.user_id
WHERE
    u.user_id IN (' . implode(',', array_map('intval',$userData)) . ')'

Error:

错误:

Couldn't execute query. 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 ')' at line 9

不能执行查询。您的SQL语法有错误;在第9行检查与MySQL服务器版本对应的手册,以获得正确的语法以使用near ')'

2 个解决方案

#1


0  

Your implode function is eventually returning an empty string and therefore you are seeing this issue.

内爆函数最终返回一个空字符串,因此您将看到这个问题。

Take this example of having empty values with the in keyword and notice similar error.

以这个使用in关键字的空值为例,注意类似的错误。

mysql> create table test(field1 int);
mysql> insert into test values (1);    
mysql> select * from test where field1 in ();

ERROR 1064 (42000): 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 ')' at line 1

#2


0  

Ugh, sorry. The issue lied with the JOINS not the IN clause. None of the IDs being requested have rows for applications. Changed JOIN to LEFT OUTER JOIN did the trick.

啊,对不起。问题在于连接,而不是IN子句。被请求的所有id都没有用于应用程序的行。把左外连接改为左外连接。

'SELECT
    u.user_id, u.email, u.first_name, u.last_name, 
    a.job_id, a.user_id, ap.job_id, ap.app_id, ap.location, 
    p.user_id, p.filename, p.selected, g.street, g.city, g.state

FROM users u

    LEFT OUTER JOIN applications ap ON ap.user_id = u.user_id
    JOIN applicants a ON a.user_id = a.user_id AND a.app_id = ap.app_id AND ap.job_id = a.job_id

    LEFT OUTER JOIN user_photos p ON u.user_id = p.user_id AND p.selected = 1
    LEFT OUTER JOIN user_general g ON u.user_id = g.user_id
WHERE
    u.user_id IN (' . implode(',', array_map('intval',$userData)) . ')'

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2015/09/15/d48880a85df33836bdc990102221ed86.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号