gpt4 book ai didi

使用 UNION 获取的数据数组的 MySQL 键名

转载 作者:行者123 更新时间:2023-11-30 23:26:13 26 4
gpt4 key购买 nike

对象

id    name    is_animal
-----------------------
1 dog 1
2 cat 1
3 chair 0
4 rabbit 1

查询

(SELECT name AS animal_name FROM objects WHERE is_animal = 1)
UNION
(SELECT name AS object_name FROM objects WHERE is_animal = 0)

结果

[animal_name] => dog
[animal_name] => cat
[animal_name] => rabbit
[animal_name] => chair // expected: [object_name] => chair

我已经在第二个 SELECT 中使用了 AS,为什么它返回 animal_name 而不是 object_name

最佳答案

使用 UNION :

(SELECT name AS animal_name,'' object_name FROM objects WHERE is_animal = 1)
UNION
(SELECT '' as animal_name, name AS object_name FROM objects WHERE is_animal = 0)

大小写:

select case is_animal when 1 name else '' end as  animal_name,
case is_animal when 0 name else '' end as object_name
from objects

关于使用 UNION 获取的数据数组的 MySQL 键名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13216601/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com