如何在单个查询中使用不同参数执行多个联接

2024-04-06

我有两个表,问题(question_id)和question_exclusion(question_type,question_sub_type,question_id)

如果我指定 Question_type 和 Question_sub_type 我就可以做到。

SELECT *
FROM question AS t1
         LEFT JOIN (SELECT t.question_id
                    FROM question_exclusion as t
                    WHERE t.question_type = 'A'
                      AND t.question_sub_type = 'A_1') AS t2
                   ON t1.question_id = t2.question_id
WHERE t2.question_id is null;

但我想要实现的是在单个查询中获取带有 questions_ids 的所有问题,以查找所有可能的问题question_type and questions_sub_type

question_type and questions_sub_type是动态参数,在查询执行之前我不知道确切的值

更新1:

实际数据:

table: question

question_id|
42
10
2
36
49

table: question_exclusion

question_type|question_sub_type|question_id|
A            | A_1             | 42
A            | A_1             | 10
A            | A_2             | 10
B            | B_1             | 36 
C            | null            | 2

预期结果:

question_type|question_sub_type|question_id
A            | A_1             | 2
A            | A_1             | 36
A            | A_1             | 49
A            | A_2             | 42
A            | A_2             | 2
A            | A_2             | 36
A            | A_2             | 49
B            | B_1             | 42
B            | B_1             | 10
B            | B_1             | 2
B            | B_1             | 49
C            | null            | 42
C            | null            | 10
C            | null            | 36
C            | null            | 49

它就像每个类型和子类型组合的列表列表 考虑排除表

例如:

type=A, sub_type=A_1 -> (select * from questions) - (select * from question_exclusion where type='A' and sub_type='A_1')
+
type=A, sub_type=A_2 -> (select * from questions) - (select * from question_exclusion where type='A' and sub_type='A_2')
+
type=B, sub_type=B_1 -> (select * from questions) - (select * from question_exclusion where type='B' and sub_type='B_2')

当然,我可以查询所有不同的(type,sub_type)并通过与 union 组合进行另一个查询

SELECT *
FROM question AS t1
         LEFT JOIN (SELECT t.question_id
                    FROM question_exclusion as t
                    WHERE t.question_type = 'A'
                      AND t.question_sub_type = 'A_1') AS t2
                   ON t1.question_id = t2.question_id
WHERE t2.question_id is null
UNION
SELECT *
FROM question AS t1
         LEFT JOIN (SELECT t.question_id
                    FROM question_exclusion as t
                    WHERE t.question_type = 'B'
                      AND t.question_sub_type = 'B_1') AS t2
                   ON t1.question_id = t2.question_id
WHERE t2.question_id is null
...
...
N times for all type and sub_type

我正在寻找另一种在单个查询中执行此操作的可靠方法


\i tmp.sql

create table question
        (question_id integer not null primary key)
        ;
INSERT INTO question(question_id) VALUES
( 42) , ( 10) , ( 2) , ( 36) , ( 49) ;

create table question_exclusion
        ( question_type text
        , question_sub_type text
        , question_id integer REFERENCES question( question_id)
        );

INSERT INTO question_exclusion(question_type, question_sub_type, question_id) VALUES
 ('A' , 'A_1' , 42 ) , ('A' , 'A_2' , 10 ) , ('B' , 'B_1' , 36  ) , ('C' , null  , 2 ) ;

WITH types AS (
        select distinct question_type, question_sub_type
        FROM question_exclusion
        )
SELECT t.question_type, t.question_sub_type, q.question_id
FROM question q
JOIN types t ON NOT EXISTS (
        SELECT * FROM question_exclusion x
        WHERE 1=1
        AND x.question_id = q.question_id
        AND x.question_type = t.question_type
        AND x.question_sub_type = t.question_sub_type
        )
ORDER BY t.question_type, t.question_sub_type
        ;

修改的:


WITH types AS (
        select distinct question_type, question_sub_type
        FROM question_exclusion
        )
SELECT t.question_type, t.question_sub_type, q.question_id
FROM question q
CROSS JOIN types t
WHERE NOT EXISTS (
        SELECT * FROM question_exclusion x
        WHERE 1=1
        AND x.question_id = q.question_id
        AND x.question_type = t.question_type
        AND x.question_sub_type = t.question_sub_type
        )
ORDER BY t.question_type, t.question_sub_type
        ;

与以下没有什么不同


WITH types AS (
        select distinct question_type, question_sub_type
        FROM question_exclusion
        )
SELECT t.question_type, t.question_sub_type, q.question_id
FROM question q
CROSS JOIN types t
WHERE NOT EXISTS (
        SELECT * FROM question_exclusion x
        WHERE 1=1
        AND x.question_id = q.question_id
        AND (x.question_type, x.question_sub_type) IS NOT DISTINCT FROM
            (t.question_type, t.question_sub_type)
        )
ORDER BY t.question_type, t.question_sub_type
        ;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在单个查询中使用不同参数执行多个联接 的相关文章

  • 插入记录后如何从SQL Server获取Identity值

    我在数据库中添加一条记录identity价值 我想在插入后获取身份值 我不想通过存储过程来做到这一点 这是我的代码 SQLString INSERT INTO myTable SQLString Cal1 Cal2 Cal3 Cal4 SQ
  • 获取mysql中逗号分隔行中不同值的计数

    一个表 Jobs 有 2 列 JobId 城市 当我们保存工作时 工作位置可能是多个城市 如下所示 JobId City 1 New York 2 New York Ohio Virginia 3 New York Virginia 我如何
  • 在Oracle中使用IW和MM

    我使用 IW 表示每周结果 使用 MM 表示每月结果 但我总是收到错误 ORA 00979 not a GROUP BY expression 00979 00000 not a GROUP BY expression 我的疑问是这些 We
  • 将DataTable批量插入postgreSQL表中

    在 SQL 中 我们执行类似的操作来批量插入数据表 SqlBulkCopy copy new SqlBulkCopy sqlCon copy DestinationTableName strDestinationTable copy Wri
  • SQL Server使用in关键字传递字符串数组查询

    我认为 IN 子句不能接受具有多个值的绑定参数 Oracle 不能 需要几分钟 查询是 declare setting varchar max set setting Sales Entry Grid Cursor Customer Man
  • 解析错误:语法错误,意外的 T_RETURN [关闭]

    这个问题不太可能对任何未来的访客有帮助 它只与一个较小的地理区域 一个特定的时间点或一个非常狭窄的情况相关 通常不适用于全世界的互联网受众 为了帮助使这个问题更广泛地适用 访问帮助中心 help reopen questions 遇到这个问
  • 如何创建没有循环关系的树形表?

    CREATE TABLE TREE node1 id UUID REFERENCES nodes object id NOT NULL node2 id UUID REFERENCES nodes object id NOT NULL CO
  • Ruby ActiveRecord 和 sql 元组支持

    ActiveRecord 是否支持 where 子句中的元组 假设底层数据库支持 结果 where 子句看起来像这样 where name address in John 123 Main St I tried Person where n
  • 如何在 PostgreSQL 中返回不同时区的当前日期

    我正在开发一个使用东部时间并将数据库设置为太平洋时间的应用程序 这已经引起了一些问题 但我们被告知不可能有其他方式 所以我们只能解决它 不管怎样 我遇到的麻烦之一就是获取今天的约会 由于数据库位于太平洋 如果我使用以下命令询问今天的日期cu
  • 计算2个日期之间每个日期的记录数

    我必须创建一个查询来返回多轴图表的结果 我需要计算为 2 个日期之间的每个日期创建的 ID 数量 我试过这个 DECLARE StartDate datetime2 7 11 1 2020 EndDate datetime2 7 2 22
  • Django 独特的不工作

    我在从查询中过滤掉重复项时遇到问题 我正在使用 Django 1 4 和 Postgres 8 4 13 我在我的模型对象上使用这个查询 它是一个 jquery 自动完成 term request GET get term field re
  • 针对约 225 万行的单表选择查询的优化技术?

    我有一个在 InnoDB 引擎上运行的 MySQL 表 名为squares大约有 2 250 000 行 表结构如下 squares square id int 7 unsigned NOT NULL ref coord lat doubl
  • 将 SQL Server 2008 DB 迁移到 Postgres [重复]

    这个问题在这里已经有答案了 我想将 SQL Server 2008 数据库迁移到 Postgres 有没有一种无痛的方法来做到这一点 是否有任何工具可以扫描架构和存储过程以标记兼容性问题 无痛http dbconvert com conve
  • 查看Jasper报告执行的SQL

    运行 Jasper 报表 其中 SQL 嵌入到报表文件 jrxml 中 时 是否可以看到执行的 SQL 理想情况下 我还想查看替换每个 P 占位符的值 Cheers Don JasperReports 使用 Jakarta Commons
  • 多边形内的 SQL 地理点在 STIntersect 上不返回 true(但使用 Geometry 返回 true)

    我不想仅仅为了在 STIntersect 中返回 true 而将地理数据转换为几何图形 下面是 SQL 中的代码 DECLARE point GEOGRAPHY GEOGRAPHY Point 1 1 4326 DECLARE polygo
  • 随着时间的推移累积(不重叠)——技术?

    我正在尝试找到一种更好的方法来制作水晶报告 其他人的 按组添加不重叠的时间 这显然是一个古老的问题 有没有一种技术可以得到 调整每条记录的 开始 结束 时间 以消除共同 重叠时间 亚组内 使用直接 SQL 尽管我发现我可以执行 CTE 假设
  • PostgreSQL函数中sql语言和plpgsql语言的区别

    我很新数据库开发所以我对下面的例子有一些疑问 函数 f1 语言 SQL create or replace function f1 istr varchar returns text as select hello varchar istr
  • SQL Server:如果存在会大大减慢查询速度

    正在使用SQL Server 2012 我找到了一些关于查询优化的主题 并将 EXISTS 与 COUNT 进行比较 但我找不到这个确切的问题 我有一个看起来像这样的查询 select from tblAccount as acc join
  • “WHERE”处或附近的语法错误

    创建 postgres 函数时会导致错误 如下所示 错误 WHERE 处或附近的语法错误 第 19 行 其中 s shift id shiftid 错误 错误 WHERE 处或附近的语法错误 SQL状态 42601 人物 108 请帮忙 C
  • 为什么 ISNUMERIC('.') 返回 1?

    最近我在 SQL Server 中使用 ISNUMERIC 时遇到了一个问题 导致找到了这段代码 SELECT ISNUMERIC 这会返回 1 如 true 所示 难道不应该像 false 一样返回 0 吗 See Numeric 损坏了

随机推荐

  • Oracle 数据脱敏

    我们有一个要求 即使用 Oracle 函数来屏蔽特定的表列 该函数提供持久的屏蔽输出字符串 我们尝试了Oracle Hash Function 但它没有给出String类型的返回值 我们尝试了 Oracle Random 函数 dbms r
  • Angular-防止从下拉列表中选择相同的选项

    I made this dropdown with a textarea for input in angular material dialog There I have only three options in the dropdow
  • 双击选择 PhpStorm 中的空白

    在 Sublime 中 我可以双击两个字符之间的空白 以便仅选择空白 例如在 foo bar 将导致选择 foo bar 然而在 PhpStorm 中它选择整行 是否有一个设置可以切换 以便可以通过双击来选择空白 就像我可以双击变量来选择它
  • MultiAutoCompleteTextView 不显示结果

    我的活动中有以下代码 ParseQuery
  • Android:定时器/延迟替代方案

    我想让一个图像在 60 毫秒内可见 然后不可见 然后我想让另一个图像执行相同的操作 等等 我认为我没有正确使用计时器 因为当我运行该应用程序时 两个图像会同时打开 并且当我按下使用此功能的按钮时 两个图像不会消失 这是一些示例代码 time
  • Ionic / Leaflet - 无法获取 Tiles 404 Not Found(从缓存)

    我被一个非常奇怪的问题所困扰 我在用着leaflet http leafletjs com with 角度传单指令 https github com tombatossals angular leaflet directive 在之前的应用
  • 在 Jetty 7 中将 JSESSIONID cookie 设置为 httpOnly

    我们正在运行 grails 2 0 jetty 7 6 6 并且需要将 JSESSIONID cookie 设置为 httpOnly stackoverflow 上的所有答案似乎都涉及 Servlet 3 0 需要 jetty 8 或 to
  • 正则表达式匹配 3 到 4 位数字

    我正在学习正则表达式 我正在尝试找到这个字符串 day1otlk XXXX gif 其中 4 个 X 是 3 到 4 个随机数字 这就是我到目前为止所拥有的 我接近了吗 qr day1otlk d gif i 您可以指定 3 或 4 位数字
  • Quartz 2D 与 OpenGL ES 学习曲线

    我开发 iPhone 应用程序已有几个月了 我想知道您对 Quartz 与 OpenGL ES 1 x 或 2 0 学习曲线的看法 你可以说出你的观点 我的问题是 我是一名想成为游戏开发者的人 所以先用quartz开发然后再迁移是个好主意吗
  • 如何记录 ActiveResource 使用的 URL?

    Rails ActiveResource 很棒 除了一件事 据我所知 无法查看它在幕后使用的 URL 例如 假设我有一个名为 Issue 的 ActiveResource 用于 myIssues com issues xml 上的 Web
  • 使原始的 Angular 表单控件变脏[重复]

    这个问题在这里已经有答案了 Angular 4 中有一种反应式形式 一些控制应该在某个时刻以编程方式设置 this form formBuilder group foo this form controls foo setValue foo
  • getJSON 和 $.ajax 之间的区别

    从一开始我就想说我知道THIS https stackoverflow com questions 1076013 difference between getjson and ajax in jquery问题与我的标题相同 但该用户提出了
  • 嵌套列表中特定项目的求和

    我有一个数据文件 例如 1 123 something else 2 234 something else 3 500 something else 1 891 something else 2 234 something else 3 5
  • CLDC 1.0 / MIDP 2.0 应用中的三角学

    如何在 CLDC 1 0 MIDP 2 0 应用程序中使用三角函数 我需要标准数学库中的 sin cos tan asin acos atan atan2 函数 Thanks 蚊子知道 http forums sun com thread
  • 在 IE11 中按计算机名称访问站点时显示“对象不支持属性或方法‘querySelector’”

    我在防火墙内的 Windows Server 2012 R2 主机上将 Angularjs 站点部署到 IIS 当我 RDP 进入服务器并从那里导航到 http localhost Foo 在 IE11 中 一切都按照人们的预期运行 我的页
  • 当我尝试运行 npx react-native run-android 时,任务:app:mergeDebugAssets 失败

    我正在使用 vscode 和物理 Android 设备在 React Native 上开发 Android 应用程序 在尝试使用 npx React Native Run Android 进行构建时 它不断显示以下错误 Task app m
  • 渠道有什么用?

    在查看一些 Go 代码时 我发现了以下内容 ch make chan int 我在在线教程中查找了 Go Channels 的工作原理 https tour golang org concurrency 2 https tour golan
  • jquery回调

    我需要能够在准备好后对函数的执行进行回调 jQuery document ready function execute function 1 only when finish do function 2 这样做的好方法是什么 加载文档后执行
  • Oracle InvalidOperationException - 尝试从表中选择时

    我有一个参数表 其中有一个参数来说明我的程序是否应该运行 我试图获取该值来检查函数 这是函数 private static bool shouldRun OracleCommand c conn CreateCommand c Comman
  • 如何在单个查询中使用不同参数执行多个联接

    我有两个表 问题 question id 和question exclusion question type question sub type question id 如果我指定 Question type 和 Question sub