I am quite new to SQL
and Sqlite
and I might not be doing this right, however and for academic reasons I am trying to learn the basics with a dirty database I created myself. Pardon me if the vocabulary is not correct, I am still in learning process.
I created a set of tables each with a different kind of entity but all of them with a similarity: they share multiple ocurrences of a same Foreign Key
with different values.
Table M1: Entity with 2 items:
+------------+---------+--------+-------+
Primary Key Unique ID Data1 Data2
+------------+---------+--------+-------+
1 x1 103021 103022
Table M2: Entity with 3 items:
+------------+---------+--------+-------+-------+
Primary Key Unique ID Data1 Data2 Data3
+------------+---------+--------+-------+-------+
1 y1 103021 103022 103001
All previous data columns are Foreign Keys
to a Unique Key
hereafter (Table N):
+------------+---------+--------+-------+
Primary Key Unique ID Data1 Data2
+------------+---------+--------+-------+
1 100002 ... ...
2 103001 ... ...
3 103021 ... ...
4 103022 ... ...
All I need to do is to extract all the entities which share a given unique item (My Foreign Key
). For instance given 103022
two entities would be given: x1
and y1
.
Now I have been trying several days and I have managed to get some of the info I need with a JOIN
statement.
INNER JOIN:
SELECT N.id, T1.id FROM N INNER JOIN M1 as T1 on T1.data1=N.id OR T1.data2=N.id
CROSS JOIN:
SELECT N.id, T1.id FROM N CROSS JOIN M1 as T1 WHERE T1.data1=N.id OR T1.data2=N.id
INNER JOIN
will only work if I do one table at a time and post-process it in real time with python, and I understand that CROSS JOIN
generates a cartesian product of my data and can easily use too much memory when I will add the other tables and boolean conditions. So I think it is not an option.
Are there any other ways I have not thought of?
Thank you All!