2014-12-26 71 views
1

我有一个问题,用IN键运行查询返回空。这是我的查询:带IN的MySQL查询返回空

SELECT * FROM `sc_miscellaneous` where discount_for=4 AND stud_id IN (1,2) AND status=1 

此查询返回正确的结果。但如果我使用IN (2,3)IN (2)意味着零结果。例如。

SELECT * FROM `sc_miscellaneous` where discount_for=4 AND stud_id IN (2,3) AND status=1 

sc_miscellaneous

ID Miscellaneous misc_amount discount discount_for class stud_id    status 
1 5    200  2  4   1 1,2,3,4,5,6,   1 
                  7,8,9,10,11, 
                  12,13,14,15,16, 
                  17,18,19 

2 6    500  2  4   1 1,2,3,4,5,6,7   1 

先谢谢了。

+4

stud_id是什么类型? –

+0

参考[this](http://stackoverflow.com/questions/10480568/comma-separated-values-in-mysql-in-clause)或[this](http://dba.stackexchange.com/questions/52492/mysql-using-comma-separated-values) –

回答

0

我觉得你stud_id类型是INT使其为varchar和运行代码

stud_id(int)---->change to varchar 

你有

in_array() 
+0

stud_id的类型仅为varchar。 – Krsmoorthi

0

工作,我不认为你写你的查询方式使用IN子句是正确的方法。

请点击此link

根据该文件,如果stud_id是一个整数,那么你可以使用IN Clause多个整数检查。如果stud_id = 1,那么你可以写入stud_id IN(1,2,3)。

根据您的要求,您可能必须编写多个查询来提取数据并进行比较。

+0

如果将stud_id的类型更改为int,则表示它如何允许逗号。我喜欢将所有学生ID插入一条记录中,而不是插入否。的记录。但是第一个查询工作正常,问题仅在第二个,如果我们在stud_id列中选择中心值(除了1),则意味着没有结果。 – Krsmoorthi

1

更新

使用下面的查询

SELECT * FROM `sc_miscellaneous` 
WHERE stud_id LIKE '%,2,%' OR stud_id LIKE '%,3,%' 
    OR stud_id LIKE '2,%,' OR stud_id LIKE '3,%' 
    OR stud_id LIKE '%,2' OR stud_id LIKE '%,3' 

当你有VARCHAR逗号分隔的列表。

检查

1)如果该唯一的号码是在逗号分隔的列表之间,

2),或者如果是,在开始

3),或者如果它的结尾。

+0

这也将恢复,例如,stud_id = 12或stud_id = 35。如果你要逗号分开(你不应该),那么逗号需要包含在LIKE中('%,2,%')并且您需要在该列中的值的开始和结束处添加逗号。 – Erik

+0

但是如果我们使用LIKE方式,列有'22,32'表示它也被选中。但我们需要确切的结果。 - 感谢 – Krsmoorthi

+0

@ user1059687,是的,得到了​​点,我会更新ans。不久。 –