想要一个不存在数据的空行
你好。这是针对 MySQL Workbench 6.3 的。
我试图返回 select 语句中列出的每个项目的结果列表,其中包括那些实际不存在的项目。因此,如果我在 select 语句中列出 5 项,但仅存在 3 项,我希望返回 5 行,其中 3 行包含数据,另外 2 行仅显示 null。有人可以告诉我如何编辑下面的查询来显示这一点吗?谢谢 !
select emails from table where email in (dog, frog, cat, tiger, lizard);
实际结果(仅显示实际存在的 3 封电子邮件)
dog
cat
tiger
期望的结果
dog
null
cat
tiger
null
最佳答案
The desired results are not possible.. You can't expect MySQL to return the selected records in the order they went in the IN() operator.
所以我认为当你将所需的结果更改为你知道有时在表中找不到的东西时,你会更好,我认为你正在寻找。
查询
SELECT
search_emails.email
, (
CASE
WHEN t.email IS NOT NULL
THEN 'true' ELSE 'false'
END
) AS found
FROM (
SELECT 'dog' AS email
UNION
SELECT 'frog' AS email
UNION
SELECT 'cat' AS email
UNION
SELECT 'tiger' AS email
UNION
SELECT 'lizard' AS email
) AS search_emails
LEFT JOIN
t
ON
t.email = search_emails.email
结果
| email | found |
| ------ | ----- |
| dog | true |
| cat | true |
| tiger | true |
| frog | false |
| lizard | false |
参见demo
关于MYSQL,包括空结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54596089/