如何构建查询语句

jianwu5 2012-09-21 04:15:40
有两张表:
a:

id name
1 tom
2 terry
...

b:

fid ids
1 1,2
...

如果需要根据表b的ids列找出表a对应的name,可以:

select name from a where id in (select ids from b where fis = 1);

问题是如果这样的话只能查找1=>tom,而不会出现terry。明显,mysql将上述查询语句的子查询表达成:

select name from a where id in ('1,2');

子查询解释为字符串,最后合并成一组。","号后面的语句无法对应id,所以mysql简化成:

select name from a where id in ('1');

因此永远只返回第一条记录,而不是第二条以后的记录。


我现在想问,查询语句应该怎么写才不会出现这种情况,而实在地解释成这样:

select name from a where id in (1,2);
...全文
178 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
jianwu5 2012-09-21
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]

select name from a where find_in_set (id ,(select ids from b where fis = 1))
[/Quote]
搞掂。汗,从来没用过find_in_set函数。

没有想到班主这么快回复,真是受宠若惊!!!
拜谢!祝你多收月饼!
ACMAIN_CHM 2012-09-21
  • 打赏
  • 举报
回复
select name from a where find_in_set (id ,(select ids from b where fis = 1))

56,677

社区成员

发帖
与我相关
我的任务
社区描述
MySQL相关内容讨论专区
社区管理员
  • MySQL
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧