2017-07-19 65 views
1

我有以下MySQL表不需要NULL值导致

tbl_pet_types:

+----------+-------------+ 
| pet  | type  | 
+----------+-------------+ 
| cat  | mammal  | 
| dog  | mammal  | 
| goldfish | fish  | 
| goldfish | seacreature | 
| snake | reptile  | 
+----------+-------------+ 

我有这样的查询选择一个青蛙和它的类型:

SELECT types.pet, 
group_concat(types.type separator ', ') AS type 
FROM tbl_pet_types types 
WHERE types.pet IN ('frog', 'mouse', 'goldfish'); 

由于青蛙和鼠标不是tbl_pet_types,返回的结果是:

+----------+-------------------+ 
| pet  | type    | 
+----------+-------------------+ 
| goldfish | fish, seacreature | 
+----------+-------------------+ 

但我想:

+----------+------------------+ 
| pet  | type    | 
+==========+==================+ 
| frog  | NULL    | 
+----------+------------------+ 
| mouse | NULL    | 
+----------+------------------+ 
| goldfish | fish,seacreature | 
+----------+------------------+ 

我怎样才能改变我的查询得到我想要的结果吗?

+0

尝试IFNULL()函数 – money

回答

0

试试这个,因为青蛙不tbl_pet_types出现在你需要把它INSERT到表

INSERT INTO tbl_pet_types (pet, type) 
VALUES ('frog', NULL); 

然后重新运行查询

1

使用COALESCE功能来指定,如果默认值types.petnull

SELECT COALESCE(types.pet, 'frog'), 
GROUP_CONCAT(types.type separator ', ') AS type 
FROM tbl_pet_types types 
WHERE types.pet='frog'; 
+0

感谢你这个答案。我对我原来的问题做了一些编辑。往上看。 – Brinley

0

你必须做的,一个SELECT查询检查后,一个INSERT INTO TB l_pet_types(pet,type)VALUES('frog',NULL);

SELECT只检索已经设置到数据库中的数据!

您可以查看更多在这里:https://www.w3schools.com/php/php_mysql_insert.asp

相关问题