简体   繁体   中英

MYSQL Query if a column is empty

I have the following statement but what I am trying to do is find out a way to say if its returned empty insert N/A . Would I use an if statement or set the default value in the DB?

Code:

$query = $this->db->query("SELECT f.film_id 'Film ID', f.film_name 'Film Name', u.user_first_name 'First Name', u.user_surname 'Surname', u.user_address_line1 'Address1', u.user_address_line2 'Address2', u.user_towncity 'City', u.user_us_state_id 'US State', u.user_non_us_state_county 'Non US State', u.user_country 'Country' FROM films f
INNER JOIN users u ON u.user_id = f.user_id WHERE f.active = 0");


return $query;

执行查询时,这将用N/A替换列中的空字符串。

SELECT ..., IF(column = '', 'N/A', column) AS column, ...

您可以使用和更新以将列更改为N / A,其中列为空。

UPDATE tablename SET column='N/A' WHERE column IS NULL

You can easily cover an empty column using a coalesce function like this:

SELECT 
    f.film_id 'Film ID', 
    f.film_name 'Film Name', 
    coalesce(u.user_first_name, 'N/A') 'First Name', 
    // ^^ Guessing that this might sometimes be the null column.
    u.user_surname 'Surname', 
    u.user_address_line1 'Address1', 
    u.user_address_line2 'Address2', 
    u.user_towncity 'City', 
    u.user_us_state_id 'US State', 
    u.user_non_us_state_county 'Non US State', 
    u.user_country 'Country' 
FROM 
    films f
        INNER JOIN users u 
            ON u.user_id = f.user_id 
WHERE f.active = 0

This will put in "N/A" if the first name field is null.

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