如何根据条件为空或不为空选择数据mysql 5.7
how to selected data based on condition null or not null mysql 5.7
我 table 像这样叫 my_table
+------------+-------+-------+
| product | type1 | type2 |
+------------+-------+-------+
| Banana | NULL | A1 |
| Grape | NULL | B1 |
| Watermelon | A | A1 |
| Orange | B | A1 |
+------------+-------+-------+
我想select根据他的类型做产品,如果type1为NULL则使用type 2,如果不是则使用type 1
所以预期的结果是这样的
+------------+------+
| product | type |
+------------+------+
| Banana | A1 |
| Grape | B1 |
| Watermelon | A |
| Orange | B |
+------------+------+
使用COALESCE
:
SELECT
product,
COALESCE(type1, type2) AS type
FROM yourTable;
COALESCE(a, b)
函数将 return a
,如果它不是 NULL
,否则它会退回到 returning b
.
我 table 像这样叫 my_table
+------------+-------+-------+
| product | type1 | type2 |
+------------+-------+-------+
| Banana | NULL | A1 |
| Grape | NULL | B1 |
| Watermelon | A | A1 |
| Orange | B | A1 |
+------------+-------+-------+
我想select根据他的类型做产品,如果type1为NULL则使用type 2,如果不是则使用type 1
所以预期的结果是这样的
+------------+------+
| product | type |
+------------+------+
| Banana | A1 |
| Grape | B1 |
| Watermelon | A |
| Orange | B |
+------------+------+
使用COALESCE
:
SELECT
product,
COALESCE(type1, type2) AS type
FROM yourTable;
COALESCE(a, b)
函数将 return a
,如果它不是 NULL
,否则它会退回到 returning b
.