简体   繁体   English

MySQL CASE WHEN where子句导致失败

[英]MySQL CASE WHEN where clause causes failure

I have a complex query that does multiple matches across multiple columns and then orders by relevance. 我有一个复杂的查询,可以跨多个列执行多个匹配,然后按相关性进行排序。

Everything works fine UNTIL I add WHERE 'rank' > 0 一切正常,直到我添加WHERE 'rank' > 0

This then returns an empty results set. 然后返回一个空结果集。

If I remove the 'WHERE' statement then I can see all results with the highest matches at the top. 如果我删除'WHERE'语句,那么我可以看到顶部匹配最高的所有结果。

Could someone help me work out 'WHERE' :-DI am going wrong!! 有人可以帮我解决'在哪里': - 我出错了!

SELECT *, CASE WHEN companyName = 'gfdgfs' THEN 2 ELSE 0 END 
+ CASE WHEN companyName LIKE '%gfdgfs%' THEN 1 ELSE 0 END 
+ CASE WHEN companyName = 'potato' THEN 2 ELSE 0 END 
+ CASE WHEN companyName LIKE '%potato%' THEN 1 ELSE 0 END 
+ CASE WHEN address1 = 'gfdgfs' THEN 2 ELSE 0 END 
+ CASE WHEN address1 LIKE '%gfdgfs%' THEN 1 ELSE 0 END 
+ CASE WHEN address1 = 'potato' THEN 2 ELSE 0 END 
+ CASE WHEN address1 LIKE '%potato%' THEN 1 ELSE 0 END 
AS rank 
FROM clients 
WHERE rank > 0
ORDER BY rank

EDIT 编辑

I removed the single quotes around the rank word and now get 'unknown column rank in where clause' 我删除了rank单词周围的单引号,现在获得'where子句中的未知列排名'

Remove single quotes from rank and try. rank删除单引号并尝试。 Anyway, I don't think MySQL would support WHERE clause with aliases - check this . 无论如何,我不认为MySQL会支持带别名的WHERE子句 - 检查一下

Use HAVING rather than WHERE : 使用HAVING而不是WHERE

SELECT *, CASE WHEN companyName = 'gfdgfs' THEN 2 ELSE 0 END + CASE WHEN companyName LIKE '%gfdgfs%' THEN 1 ELSE 0 END + CASE WHEN companyName = 'potato' THEN 2 ELSE 0 END + CASE WHEN companyName LIKE '%potato%' THEN 1 ELSE 0 END + CASE WHEN address1 = 'gfdgfs' THEN 2 ELSE 0 END + CASE WHEN address1 LIKE '%gfdgfs%' THEN 1 ELSE 0 END + CASE WHEN address1 = 'potato' THEN 2 ELSE 0 END + CASE WHEN address1 LIKE '%potato%' THEN 1 ELSE 0 END AS rank FROM clients HAVING rank > 0 ORDER BY rank

Try this: 尝试这个:

SELECT * 
FROM (SELECT *, CASE WHEN companyName = 'gfdgfs' THEN 2 ELSE 0 END 
              + CASE WHEN companyName LIKE '%gfdgfs%' THEN 1 ELSE 0 END 
              + CASE WHEN companyName = 'potato' THEN 2 ELSE 0 END 
              + CASE WHEN companyName LIKE '%potato%' THEN 1 ELSE 0 END 
              + CASE WHEN address1 = 'gfdgfs' THEN 2 ELSE 0 END 
              + CASE WHEN address1 LIKE '%gfdgfs%' THEN 1 ELSE 0 END 
              + CASE WHEN address1 = 'potato' THEN 2 ELSE 0 END 
              + CASE WHEN address1 LIKE '%potato%' THEN 1 ELSE 0 END 
              AS rank 
        FROM clients 
      ) AS A 
WHERE rank > 0
ORDER BY rank;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM