【发布时间】:2012-03-09 16:32:37
【问题描述】:
我需要执行一些复杂的 sql 查询,但我有点卡住了。如果有任何改变,我将使用 SQLite。
我的表结构如下:
Table G
---------
G_id (primary key) | Other cols ...
====================================
21
22
23
24
25
26
27 (no g_to_s_map)
28
.
Table S
---------
S_id (primary key) | S_num | Other cols.....
====================================
1 1101
2 1102
3 1103
4 1104
5 1105
6 1106
7 1107 (no g_to_s_map, no s_to_t_map)
8 1108 (no g_to_s_map, there IS an s_to_t_map)
9 1109 (there is an g_to_s_map, but no s_to_t map)
.
Table T
---------
T_id (primary key) | Other cols...
==================================
1
2
那我还有两个映射表:
Table G_to_S_Map (1:1 mapping, unique values of both g_id and s_id)
----------
G_id (foreign key ref g)| S_id (foreign key ref s)
===================================================
21 1
22 2
23 3
24 4
25 5
26 6
28 9
.
Table S_to_T_Map (many:1 mapping, many unique s_id to a t_id)
----------
S_id (foreign key ref s) | T_id (foreign key ref s)
===================================================
1 1
2 1
3 1
4 2
5 2
6 2
8 2
仅给定一个 T_id 和一个 G_id,我需要能够使用第一个 S_id 更新 G_to_S_Map strong> 对应于不在 G_to_S_Map
中的指定 T_id(在 S_to_T_Map 中)我首先想到的是获取与 S_to_T_Map 中的 T_id 对应的任何 S_id:
SELECT S_id FROM S_to_T_Map where T_id = GIVEN_T_ID;
然后大概我会使用左/右连接以某种方式将这些值与 G_to_S_Map 连接起来,然后查找其中一侧不存在的第一个值?然后我需要根据该 S_id 和 GIVEN_G_ID 值或其他内容插入 G_to_S_Map。
关于如何解决这个问题有什么建议吗?谢谢!
编辑:添加了一些虚拟数据:
【问题讨论】: