计算列上的MySQL IF语句

时间:2015-03-20 10:08:26

标签: mysql sql

如何在使用'Where'子句中的'IF'Statement的SQL语句中使用计算列。

我的查询在下面。我一直收到错误

Unknown column 'e_owner_id_church' in 'where clause'

SELECT idu,fname,lname,id_file,friendly_name,file_name,uploaded_by,date_uploaded,
file_last_modified,owner_id, 
CASE WHEN owned_by='church' THEN church_name WHEN owned_by='user' THEN CONCAT(fname, ' ', lname) END AS e_owner_name, 
CASE WHEN owned_by='church' THEN id_church END AS e_owner_id_church,
CASE WHEN owned_by='user' THEN idu END AS e_owner_id_user 
FROM files,file_affiliations,churches,users 
WHERE owner_id=IF(e_owner_id_church != null, e_owner_id_church, e_owner_id_user) 
GROUP BY file_id

2 个答案:

答案 0 :(得分:1)

这可以作为使用HAVING子句的解决方法:

SELECT idu
     , fname
     , lname
     , id_file
     , friendly_name
     , file_name
     , uploaded_by
     , date_uploaded
     , file_last_modified
     , owner_id
     , CASE owned_by
        WHEN 'church' THEN church_name
        WHEN 'user' THEN CONCAT(fname, ' ', lname)
       END AS e_owner_name
     , CASE owned_by
        WHEN 'church' THEN id_church
        ELSE NULL
       END AS e_owner_id_church
     , CASE owned_by
        WHEN 'user' THEN idu
        ELSE NULL
       END AS e_owner_id_user
FROM files
   , file_affiliations
   , churches
   , users 
GROUP BY file_id
HAVING owner_id = IFNULL(e_owner_id_church, e_owner_id_user)

我想警告你,这个查询是不是标准SQL,实际上它选择既不包含在GROUP BY子句中的字段也不是组函数的结果

最后,我认为上述内容可以简化为:

SELECT idu
     , fname
     , lname
     , id_file
     , friendly_name
     , file_name
     , uploaded_by
     , date_uploaded
     , file_last_modified
     , owner_id
     , CASE owned_by
        WHEN 'church' THEN church_name
        WHEN 'user' THEN CONCAT(fname, ' ', lname)
        ELSE NULL
       END AS e_owner_name
     , CASE owned_by
        WHEN 'church' THEN id_church
        WHEN 'user' THEN idu
       END AS e_owner_id
FROM files
   , file_affiliations
   , churches
   , users 
GROUP BY file_id
HAVING owner_id = e_owner_id

答案 1 :(得分:0)

没有尝试过,但这样的事情应该有效:

SELECT idu,fname,lname,id_file,friendly_name,file_name,uploaded_by,date_uploaded,
file_last_modified,owner_id, 
CASE WHEN owned_by='church' THEN church_name WHEN owned_by='user' THEN CONCAT(fname, ' ', lname) END AS e_owner_name, 
CASE WHEN owned_by='church' THEN id_church END AS e_owner_id_church,
CASE WHEN owned_by='user' THEN idu END AS e_owner_id_user 
FROM files,file_affiliations,churches,users 

GROUP BY file_id
HAVING owner_id = COALESCE(e_owner_id_church, e_owner_id_church, e_owner_id_user)