You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SQL查询:存在table2指向table1的外键记录时返回所有匹配table2数据

SQL关联查询结果不匹配问题

现有表结构

第一张表table1结构:

table1
-------------------------
|id|  rec    | other_rec|
-------------------------
|1 | record1 | record6  |
|2 | record2 | record8  |
|3 | record4 | record0  |
|4 | record5 | record2  |
|n |   ...   |   ...    |
------------------------

第二张表table2结构:

table2
-------------------------------------------------
|id|  table_nr_1_foreign_key | rec_1  | rec_2   |
-------------------------------------------------
|1 | table_nr_1_key_1        |record1 | rt1     |
|2 | table_nr_1_key_2        |record2 | rt2     |
|3 | table_nr_1_key_2        |record4 | rt3     |
|4 | table_nr_1_key_3        |record5 | rt4     |
|5 | table_nr_1_key_2        |record6 | rt5     |
|n | table_nr_1_key_n        |  ...   |   ...   |
-------------------------------------------------

已编写的查询语句

SELECT t.id,
       t.rec,
       t.other_rec,
       t2.rec_1
FROM table1 t1
JOIN ...[other table]
   and ...[conditions start]
   and ...
   and ...[conditions end]
LEFT JOIN table2 t2 ON t.id = table_nr_1_foreign_key
AND t2.rec_2 = any(array['rt2'])
where ...[other condition]

需求与实际结果差异

需求:只要table2中存在至少一条指向对应table1记录的外键数据,就查询出该外键对应的所有table2关联记录。
期望结果:

data1,..., rt2
data1,..., rt3
data1,..., rt5
...

实际运行仅得到如下结果:

data1,..., rt2

问题更新说明

因经验不足,没有使用单条SQL实现该需求,通过两次SQL查询完成需求:

  1. 首先查询table1的主记录数据
  2. 再将table1主键列表传入IN查询,获取所有匹配的table2记录
    该问题可关闭/删除。

内容的提问来源于stack exchange,提问作者miroana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 12:36:03