mardi 1 septembre 2015

How to combine two queries and use results of first one as output for the second

Tables

I have the following tables:

 entite              var_entite                 variation
ID | NAME        ID_entite|id_var                ID | NAME
1  | x1            1      |    1                  1 | y1
2  | x2            1      |    2                  2 | y2
3  | x3            1      |    3                  3 | y3
                   2      |    1                  4 | y4
                   2      |    4                  5 | y5
                   3      |    2
                   3      |    5


Schema

CREATE TABLE ENTITE (ID PRIMARY KEY NOT NULL, NAME STRING)

CREATE TABLE VAR_ENTITE(ID_ENTITE INTEGER NOT NULL, 
                        ID_VARIATION INTEGER NOT NULL, 
                        FOREIGN KEY (ID_ENTITE) REFERENCES ENTITE(ID),
                        FOREIGN KEY (ID_VARIATION) REFERENCES VARIATIONS(ID);

CREATE TABLE VARIATIONS (ID PRIMARY KEY NOT NULL, NAME STRING)


Problem

I am using sqlite3. the ? represent the input variables.

1- For every entity x in table entite we want to select its variations y

SELECT e.id, e.name, v.name FROM var_entite ve 
       JOIN entite as e ON e.id_entite = ve.id_entite 
       JOIN variations as v ON v.id = ve.id_var;

2- For every selected entity in the previous query weselect all the rest entities having the same varitions.

SELECT e.id, e.name, v.name FROM var_entite ve 
       JOIN entite as e ON e.id = ve.id 
       JOIN variations as v ON v.id = ve.id_var
       where e.id <> ? and v.name =? ;

  • e.id_entite <> ? for the rest of entities having a different entity from query 1

  • v.name =? if an entity has the same variation as the one returned in 1 then we select it

My questions are the following:

  • How can we combine these 2 queries in order to get the same results?
  • If we combine the queries will the querying become faster?

Example

Query 1:

1,x1,y1
1,x1,y2
1,x1,y3
2,x2,y1
2,x2,y4
3,x3,y2
3,x3,y5

Query 2 outputs for entity with id = 1

    2,x2,y1
    3,x3,y2

Query 2 output for entity with id = 2

    1,x1,y1
    etc.

Aucun commentaire:

Enregistrer un commentaire