我有以下MySQL表
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');
由于frog和mouse不是tbl_pet_types,返回的结果是:
+----------+-------------------+
| pet | type |
+----------+-------------------+
| goldfish | fish, seacreature |
+----------+-------------------+
但我想:
+----------+------------------+
| pet | type |
+==========+==================+
| frog | NULL |
+----------+------------------+
| mouse | NULL |
+----------+------------------+
| goldfish | fish,seacreature |
+----------+------------------+
如何更改查询以获得我想要的结果?
答案 0 :(得分:1)
如果types.pet
为null
,请使用COALESCE功能指定默认值:
SELECT COALESCE(types.pet, 'frog'),
GROUP_CONCAT(types.type separator ', ') AS type
FROM tbl_pet_types types
WHERE types.pet='frog';
答案 1 :(得分:0)
试试这个,因为青蛙没有出现在tbl_pet_types中,你需要INSERT
进入表格
INSERT INTO tbl_pet_types (pet, type)
VALUES ('frog', NULL);
然后重新运行您的查询
答案 2 :(得分:0)
在SELECT查询检查后,您必须执行INSERT INTO tbl_pet_types(pet,type)VALUES('frog',NULL);
SELECT仅检索已设置到数据库中的数据!
您可以在此处查看更多内容:https://www.w3schools.com/php/php_mysql_insert.asp