首页 > 解决方案 > 在一列中选择可选数量的值

问题描述

我试图查看是否可以在满足某个条件时将多个值查询到别名中,同时在满足不同条件时插入一个值。我想看看这是否可能不做子查询。

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

标签: sqlpostgresql

解决方案


如果您只需要知道橙色的东西而它们之间没有任何关系,我认为一个简单的联合全部(或联合)查询可以产生结果:

SELECT name AS orange_stuff
FROM cats
WHERE color = 'orange'
UNION ALL
SELECT name AS orange_stuff
FROM toys 
WHERE color = 'orange'

推荐阅读