读书人

怎么构建查询语句

发布时间: 2012-09-24 13:49:41 作者: rapoo

如何构建查询语句
有两张表:
a:

SQL code
id name1  tom2  terry...

b:
SQL code
fid  ids1    1,2...

如果需要根据表b的ids列找出表a对应的name,可以:
SQL code
select name from a where id in (select ids from b where fis = 1);

问题是如果这样的话只能查找1=>tom,而不会出现terry。明显,mysql将上述查询语句的子查询表达成:
SQL code
select name from a where id in ('1,2');

子查询解释为字符串,最后合并成一组。","号后面的语句无法对应id,所以mysql简化成:
SQL code
select name from a where id in ('1');

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


我现在想问,查询语句应该怎么写才不会出现这种情况,而实在地解释成这样:
SQL code
select name from a where id in (1,2);


[解决办法]
select name from a where find_in_set (id ,(select ids from b where fis = 1))

读书人网 >Mysql

热点推荐