计算mysql查询中所有匹配的字段

时间:2012-04-16 22:08:41

标签: mysql

我的问题是:我有一个像这样的mysql查询:

SELECT student_id, name, email 
FROM student 
WHERE student_id IN ('1', '2', '3') 
    OR name LIKE '%Nick%' 
    OR email LIKE '%gmail.com%'

如何以mysql返回的列的形式获取a中匹配字段的数量 像这样:

   ID NAME  EMAIL           MATCHED  
1. 1  Nick  nick@gmail.com  3  
2. 5  Nick  nick@yahoo.com  1  
3. 2  David david@gmail.com 2  

谢谢!

2 个答案:

答案 0 :(得分:7)

这很难看,但有点像

SELECT student_id, name, email,
   IF(student_id IN (1,2,3), 1, 0) +
   IF(name LIKE '%Nick%', 1, 0) +
   IF(email LIKE '%gmail.com%', 1, 0) AS matched
etc...

应该这样做。

答案 1 :(得分:2)

这应该有效

SELECT student_id, name, email, 
     (
        CASE WHEN student_id IN ('1', '2', '3') THEN 1 END +
        CASE WHEN name LIKE '%Nick%' THEN 1 END +
        CASE WHEN email LIKE '%gmail.com%' THEN 1 END
     ) as matched
FROM student 
WHERE student_id IN ('1', '2', '3') 
    OR name LIKE '%Nick%' 
    OR email LIKE '%gmail.com%'