sql - 在一列中选择可选数量的值
问题描述
我试图查看是否可以在满足某个条件时将多个值查询到别名中,同时在满足不同条件时插入一个值。我想看看这是否可能不做子查询。
我正在使用 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
解决方案
如果您只需要知道橙色的东西而它们之间没有任何关系,我认为一个简单的联合全部(或联合)查询可以产生结果:
SELECT name AS orange_stuff
FROM cats
WHERE color = 'orange'
UNION ALL
SELECT name AS orange_stuff
FROM toys
WHERE color = 'orange'
推荐阅读
- yocto - Yocto 和 TPM:最终图像上缺少 /dev/tpm
- prometheus - Prometheus:错误:404,响应正文:尝试使用 PushGateway 推送指标时找不到 404 页面
- r - R - shp 文件中的 rgdal ERRO - 层
- javascript - eventlistener beforeunload 在反应中不起作用
- python - 重叠图例:如何将 geopandas 图例放在地图旁边?
- sql-server - 如何返回数据库中不可用的搜索值?
- python - 从 pandas 数据框中找到与用户输入最相似的行
- html - 具有相同 Vue 模型实例的多个表单,单击时总是获取第一个表单数据
- reactjs - 带有条件运算符的多个内联 If-Else
- android - Firebase Analytics 无法在真实设备中运行