简体   繁体   中英

MySQL query with conditional SELECT arguments - Unknown column in where clause

SQL Query:

SELECT          
    IF(
       pu.userPayeeType='fiziska', 
       CONCAT(pu.userName,' ', pu.userLastName), 
       pu.userCompanyName
    ) AS supplierName
FROM 
    publicUsers pu  
WHERE 
    supplierName LIKE  '%Jo%'

Error Code: 1054. Unknown column 'supplierName' in 'where clause'

From what I understand, SQL query is evaluated and parsed "somewhat" from the bottom up which means that the WHERE clause does not yet know what an alias "supplierName" is and throws this error.

How can I make a conditional SELECT with regards to the column contents?

Database contents:

userPayeeType | userName | userLastName | userCompanyName
--------------+----------+--------------+------------------
   'fiziska'  |  John    | Doe          | 
--------------+----------+--------------+------------------
   'fiziska'  |  Joe     | Pie          |  
--------------+----------+--------------+------------------
   'other'    |          |              |  'Joes Company, Ltd'
--------------+----------+--------------+------------------

Preferred results:

Row #  | supplierName 
-------+--------------------
  1.   | 'John Doe'
-------+--------------------
  2.   | 'Joe Pie'
-------+--------------------
  3.   | 'Joes Company, Ltd'

Am I missing something with the syntax?

You cannot use alias in the where clause. You can use coalesce to get the first non null value.

SELECT          
    IF(
       pu.userPayeeType='fiziska', 
       CONCAT(pu.userName,' ', pu.userLastName), 
       pu.userCompanyName
    ) AS supplierName
FROM 
    publicUsers pu  
WHERE 
    coalesce(pu.userName,pu.userCompanyName) LIKE  '%Jo%';

Or even a simple where with OR between columns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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