3

我的问题是下一个:我有一个这样的 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返回的列的形式获取匹配字段的数量 像这样:

   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  

谢谢!!

4

2 回答 2

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...

应该做的伎俩。

于 2012-04-16T22:16:34.903 回答
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%'
于 2012-04-16T22:12:10.307 回答