sql - 在一列中选择可选数量的值

标签 sql postgresql

我正在尝试查看是否可以在满足特定条件时将多个值查询到别名中,而在满足不同条件时插入一个值。我想看看这是否可以在不执行子查询的情况下实现。

我正在使用 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/

相关文章:

sql - oracle sql TO_CHAR 函数在某些情况下添加尾随空白

python - 错误 : parameters are of unsupported type By scrapy sql insert

postgresql - 你如何让一个ddl进入postgres

python - django 无法连接到 RDS postgresql

postgresql - PostgreSQL 9.1 中 SET TABLESPACE 上的表锁?

SQL:按列分区并在分区内随机排列结果

php - 使用 CI 语句中的 where 防止重复结果

java - log4j 与 oracle 给出异常 - 无效的 sql 语句

sql - 带有 DNS 记录的 Postgresql 数据库 : how to mass-increase serial

ruby-on-rails - PostgreSQL 所有权错误