2017-07-19 106 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

相關問題