简体   繁体   English

MySQL在WHERE语句中使用COALESCE或IFNULL选择非NULL值

[英]MySQL select non-NULL values with COALESCE or IFNULL in a WHERE statement

I'm building a summary in a table that I self-join in order to count the rows corresponding on certain values (in TikiWiki CMS, tracker application). 我正在自我连接的表格中建立摘要,以便计算在某些值(在TikiWiki CMS,跟踪器应用程序)中对应的行。 But I have a case where there are two columns that can have the same values, and I need SQL to take the first non-NULL value in a specific order. 但是我有两种情况,它们可以具有相同的值,并且我需要SQL以特定的顺序获取第一个非NULL值。

Here is an example of the table tiki_tracker_item_fields where I work: 这是我工作的表tiki_tracker_item_fields的示例:

 itemId  | fieldId  | value   
==========================
41       | 236      | Paris   
41       | 213      | Paris  
14       | 236      |         
14       | 213      | Paris  
25       | 236      | Paris     
25       | 213      |       

In the query I want to count all lines that have "Paris" as value, either in field Id 236 or field ID 213. The result here should be: 3. 在查询中,我要计算字段ID 236或字段ID 213中所有具有“巴黎”作为值的行。这里的结果应该是:3。

There is my request: 有我的要求:

 SELECT COUNT(*) AS sp_actions           
FROM                                    
  `tiki_tracker_item_fields` AS actions 
WHERE                                   
  COALESCE(                             
    actions.fieldId = 236,              
    actions.fieldId = 213               
  )                                     
AND actions.value = 'Paris'                  

So this works when I have 'Paris' for field 236, but not when I have Paris for field 213. 因此,当我在字段236中使用“巴黎”时,此方法有效,但是当我在字段213中具有巴黎时,则无效。

And I'm not even sure I could use COALESCE this way, all examples I found put COALESCE in the SELECT statement. 而且我甚至不确定我是否可以通过这种方式使用COALESCE,我发现的所有示例都将COALESCE放在SELECT语句中。

Then there are the performance issues... 然后是性能问题...

You can use count (distinct) with a case : 您可以将count (distinct)case一起使用:

select 
    count(distinct case when value = 'Paris' then itemId end) cnt
from `tiki_tracker_item_fields`
where fieldId in (236,213);

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

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