MySQL IN 问题
我正在尝试使用 IN 内另一个字段的值。
SELECT types.id, title, auth_users.types
FROM types
LEFT JOIN auth_users ON auth_users.id IN (8,9)
WHERE types.id IN (1,2,3)
GROUP BY types.id
有效
SELECT types.id, title, auth_users.types
FROM types
LEFT JOIN auth_users ON auth_users.id IN (8,9)
WHERE types.id IN (auth_users.types)
GROUP BY types.id
无效
http://pastebin.com/m76ae0596 更多信息可在此处找到
auth_users.types = 1,2,3
I'm trying to use the value of another field inside an IN.
SELECT types.id, title, auth_users.types
FROM types
LEFT JOIN auth_users ON auth_users.id IN (8,9)
WHERE types.id IN (1,2,3)
GROUP BY types.id
Works
SELECT types.id, title, auth_users.types
FROM types
LEFT JOIN auth_users ON auth_users.id IN (8,9)
WHERE types.id IN (auth_users.types)
GROUP BY types.id
Does not work
http://pastebin.com/m76ae0596 More info can be found here
auth_users.types = 1,2,3
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不幸的是,
IN (...)
不会尝试解析 varchar-field 值来提取您想要匹配的值。它基本上只是检查“types.id”是否是“1,2,3”之一(即不是1,2或3,而是实际的单个值“1,2,3”。)
解决这个问题的一种方法是数据库中有一个函数返回结果集,并接受该 varchar 值,解析它,并为您的示例返回 3 行。
除此之外,您需要重写以使用 LIKE(这会执行得很糟糕),或者您需要自己解析这些值并将结果直接放入 SQL 中。
Unfortunately,
IN (...)
won't attempt to parse a varchar-field value to extract the values you want to match against.It basically just checks if "types.id" is one of "1, 2, 3" (ie. not 1, 2 or 3, but the actual single value "1, 2, 3".)
One way to solve this would be to have a function in the database that returns a resultset, and takes that varchar value in, parses it, and returns 3 rows for your example.
Other than that, you need to either rewrite to use LIKE (which will perform horribly), or you need to parse those values yourself and place the result into the SQL directly.
尝试行子查询:
编辑:
实际上,看看你的pastebin,你是否将“1,2,3”存储在单行中作为varchar? 那是行不通的。
Try row subqueries:
EDIT:
Actually, looking at your pastebin, are you storing "1,2,3" in a single row as a varchar? That's not going to work.
我猜他正在寻找一个简单的连接
LEFT JOIN auth_users ON types.id = auth_users.types
WHERE auth_users.id IN (8,9)
I guess he is looking for a simple join
LEFT JOIN auth_users ON types.id = auth_users.types
WHERE auth_users.id IN (8,9)
您需要使用
FIND_IN_SET
- 请参阅此问题:MySql : Select使用 IN 运算符的语句You need to use
FIND_IN_SET
- see this question: MySql : Select statement using IN operator