在一栏中选择任意数量的值

时间:2019-06-08 02:33:39

标签: 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语句的设置方式是,当两次都选择toy.name上的“ Garfield”时

 orange_stuff 
--------------
 Garfield
 hay
 Garfield

想看是否有可能,而无需子查询来获取:

 orange_stuff 
--------------
 Garfield
 hay
 yarn

1 个答案:

答案 0 :(得分:2)

如果您只需要了解橙色事物,而彼此之间没有任何关系,我认为一个简单的联合所有(或联合)查询可能会产生结果:

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