简体   繁体   中英

Mysql: How do I fill in null values in one row with values from another row in the same table?

I have a table with an id column that references a row from the same table that represents a set of default values the row should return if any of the values are NULL. For example:

'content'
id | a   | b   | default_id
----------------------------------
1  | 33  | 55  | NULL
2  | NULL| 11  | 1

So I want to query row 2 in a way that I get back a result with 'a' = 33 and 'b' = 11. Is there some simple way to do this?

You may want to use the COALESCE() function, whick returns the first non-NULL value in the list:

SELECT      COALESCE(c1.a, c2.a) a ,
            COALESCE(c1.b, c2.b) b
FROM        content c1
LEFT JOIN   content c2 ON (c2.id = c1.default_id)
WHERE       c1.id = 2;

Test case:

CREATE TABLE content (id int, a int, b int, default_id int);
INSERT INTO content VALUES (1, 33, 55, NULL);
INSERT INTO content VALUES (2, NULL, 11, 1);

Result:

+------+------+
| a    | b    |
+------+------+
|   33 |   11 |
+------+------+
1 row in set (0.00 sec)
select t1.id
      ,coalesce(t1.a, t2.a) as a
      ,coalesce(t1.b, t2.b) as b
  from content t1 
  left outer 
  join content t2 on(t1.default_id = t2.id)
 where t1.id = 2;

SELECT t1.id, IFNULL(t1.a, t2.a), IFNULL(t1.b,t2.b)
FROM content t1
LEFT JOIN content t2 ON (t2.id = t1.default_id)
WHERE t1.id = 2

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