I have a bit of a complicated sql query I need to do, and I’m a bit stuck. I’m using SQLite if that changes anything.
I have the following table structure:
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
Then I also have two mapping tables:
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
Given only a T_id and a G_id, I need to be able to update the G_to_S_Map with the first S_id corresponding to the specified T_id (in the S_to_T_Map) that is NOT in the G_to_S_Map
The first thing I was thinking of was just getting any S_id‘s that corresponded to the T_id in the S_to_T_Map:
SELECT S_id FROM S_to_T_Map where T_id = GIVEN_T_ID;
Then presumably I would join those values somehow with the G_to_S_Map using a left/right join maybe, and then look for the first value which doesn’t exist on one of the sides? Then I’d need to do an insert into the G_to_S_Map based on that S_id and the GIVEN_G_ID value or something.
Any suggestions on how to go about this? Thanks!
Edit: Added some dummy data:
I believe this should work:
EDIT:
If you’re wanting to do the order by a different table, use this version:
(As an aside, I really hope your tables aren’t actually named like this, because that’s a terrible thing to do. The use of
Map, especially, should probably be avoided)EDIT:
Here’s some example test data. Have I missed something? Did I conceptualize the relationships incorrectly?
Resulting joined data:
(CTEs used to generate cross-join test data)
EDIT:
Ah, okay, now I get the problem. My issue was that I was assuming there was some sort of many-one relationship between
SandG. As this is not the case, use this amended statement:Specficially, the line checking
G_To_S_Mapfor a row containing theG_Idneeded to be switched from using anANDto anOR– the key requirement which had not been specified previously was the fact that bothG_IdandS_Idwere unique inG_To_S_Map.This statement will not insert a line if either the provided
G_Idhas been mapped previously, or if allS_Ids mapped to the givenT_Idhave been mapped.