我有一张家长device的桌子,以及division张桌子. 中间是STAKS和ctrltab表,每个表都具有与device匹配的属性Device_id,以及连接到pipe_division表的PIPE_Divition_id. 编辑:应要求,我已在下面添加了示例表

设备表

device_id | name   | board_number 
--------------------------------
23         Stop1    10
24         Stop2    11
25         Ctrltab1 11
26         Rand_dev 8 

停靠台

device_id | label        | pipe_division_id | length
23          Stop1: Piano   305                16
24          Stop2: Buffet  306                16

CtrlTab表

device_id | label    | pipe_division_id | ctrl_function
25          Ctrltab1     305              open_window 

管道分割表

pipe_division_id | label     | position
305                Lower Box    underneath the stairs
306                Upper Box    above the stairs
307                Side Box     To the left of the console in the closet

查询的预期结果:

name   | board_number | label
Stop1    10             Lower Box
Stop2    11             Upper Box
Ctrltab1 11             Lower Box

本质上,我想 Select device表中板号大于10的所有器件,这些器件的管道_分区_id是通过连接它们的STOP或ctrltab表找到的.

我试过了

Select name, board_number, pd.label 
from device d 
JOIN stops s ON s.device_id = d.device_id 
JOIN ctrltab ct ON ct.device_id = d.device_id 
JOIN pipe_division_id pd ON (s.pipe_division_id = pd.pipe_division_id 
                         OR ct.pipe_division_id = pd.pipe_division_id)

但这并没有带来任何结果,我想这个OR语句是无效的?我宁愿避免使用UNION,因为真正的查询非常长,并且我不想为了在查找PIPE_DIVATION标签方面的微小差异而重复所有文本.

推荐答案

SELECT d.name, d.board_number, COALESCE(pd1.label, pd2.label) AS label
FROM device d
LEFT JOIN stop s ON s.device_id = d.device_id
LEFT JOIN pipe_division pd1 ON s.pipe_division_id = pd1.pipe_division_id
LEFT JOIN ctrltab ct ON ct.device_id = d.device_id
LEFT JOIN pipe_division pd2 ON ct.pipe_division_id = pd2.pipe_division_id
WHERE d.board_number > 10;

Dbfiddle

Sql相关问答推荐

如何解决Error:operator is not unique:unknown—unknown在一个动态SQL查询?""""

在Oracle SQL中将列值转换为行

用于过滤嵌套对象或数组中的JSON数据的WHERE条件

数据库SQL-CTE命名空间(错误?)使用临时视图

需要从键-值对数据中提取值

通过对象分离实现原子性

Postgres jsonpath运算符的变量替换,如_regex?

从重复值中获取最新值

日期逻辑(查找过go 90 天内的第一个匹配行)

使用多个数据库调用重载 CQRS 模式

Postgresql 具有相似行为和模式行为的问题

什么是 100.它与 100 有什么区别?

如何在 SQL 中将两行(或多行)jsonb 数组合并为一行

计算 BigQuery 中列的中值差 - 分析函数不能作为聚合函数的参数

BigQuery导航函数计算ID

Postgres如何在一个日历周中前进和回填值

比使用NOT EXISTS更高效的SQL删除方法是什么?

所有列分组的简写?

Clob 问题 - 将 clob 列拆分为多行

PostgreSQL 如何在一组项目及其数量上找到完全相同的订单?