我正在尝试查看是否可以在满足特定条件时将多个值查询到别名中,而在满足不同条件时插入一个值。我想看看这是否可以在不执行子查询的情况下实现。
我正在使用 postgreSQL 11,我最近开始学习 SQL。
为了练习,我使用了来自 SQLZOO 的示例,涉及 3 个单独的表-
cats (id, name, color, breed)
toys (id, name, price, color)
cattoys (id, cat_id, toy_id)
我已经为这些表创建了我自己的数据,我想看看是否可以在一个列中包含特定颜色的任何东西(猫或玩具),而无需执行子查询。
在我使用的数据中,每个表中有 5 行。测试-
'Garfield' is the only 'orange' cat
'hay' and 'yarn' are the only 'orange' toys
'Garfield' has both hay and yarn (the only toys for Garfield)
'Ozzie' has yarn (the only toy for Ozzie)
是否可以运行一个查询,得到类似于以下的输出:
orange_stuff
--------------
Garfield
hay
yarn
我已经接近了,但我无法将我的 CASE 语句写下来,如果 cats.color 和 toys.color 都是“orange”,则将这两个项目插入到我的别名“orange_stuff”中。
第一次尝试:
SELECT
CASE
WHEN cats.color = 'orange' AND toys.color = 'color' THEN cats.name, toys.name
WHEN cats.color = 'orange' THEN cats.name
WHEN toys.color = 'orange' THEN toys.name
END AS orange_stuff
FROM
cats
JOIN
cattoys ON cattoys.cat_id = cats.id
JOIN
toys ON toys.id = cattoys.toy_id
WHERE
cats.color = 'orange' OR toys.color= 'orange';
这将不起作用,因为在第一个 WHEN 语句中尝试返回两个参数时发生错误
替代尝试:
SELECT
CASE
WHEN cats.color = 'orange' THEN cats.name
WHEN toys.color = 'orange' THEN toys.name
END AS orange_stuff
FROM
cats
JOIN
cattoys ON cattoys.cat_id = cats.id
JOIN
toys ON toys.id = cattoys.toy_id
WHERE
cats.color = 'orange' OR toys.color= 'orange';
这几乎可以解决问题,但是 CASE 语句的设置方式,当它两次选择“Garfield”而不是 toys.name 时
orange_stuff
--------------
Garfield
hay
Garfield
想看看是否可以,不用子查询获取:
orange_stuff
--------------
Garfield
hay
yarn
最佳答案
如果您只需要知道橙色的事物而它们之间没有任何关系,我认为一个简单的 union all(或 union)查询可以产生结果:
SELECT name AS orange_stuff
FROM cats
WHERE color = 'orange'
UNION ALL
SELECT name AS orange_stuff
FROM toys
WHERE color = 'orange'
关于sql - 在一列中选择可选数量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56502974/