What is the standard SQL Query to retrieve the intersection of tables?

前端 未结 9 554
谎友^
谎友^ 2021-02-02 03:57

Selecting the union:

select * from table1 
union 
select * from table1_backup 

What is the query to select the intersection?

相关标签:
9条回答
  • 2021-02-02 04:49

    For questions like this, I tend to go back to this visual resource:

    A Visual Explanation of SQL Joins

    0 讨论(0)
  • 2021-02-02 04:51

    inner join i think: suppose T1 and T2 have the same structure:

    select T1.* from T1 inner join T2 on T1.pkField = T2.pkField

    0 讨论(0)
  • 2021-02-02 04:53

    here is a solution for mySQL:

    CREATE TABLE table1(
    id INT(10),
    fk_id INT(10),
    PRIMARY KEY (id, fk_id),
    FOREIGN KEY table1(id) REFERENCES another_table(id),
    FOREIGN KEY table1(fk_id) REFERENCES other_table(id)
    );
    
    SELECT table1.* FROM table1 as t0
    INNER JOIN table1 as a ON (t0.id = a.id and fk_id=1)
    INNER JOIN table1 as b ON (t0.id = b.id and fk_id=2)
    INNER JOIN table1 as c ON (t0.id = c.id and fk_id=3)
    ORDER BY table1.id;
    

    Basically you have an table of mathematical subsets (ie. 1={1, 2 ,3}, 2={3, 4, 2}, ... , n={1, 4, 7}) with an attribute id, which is the set number, and fk_ id, which references a PRIMARY KEY of a table of elements, the superset (meaning possible values for the numbers in the curly braces). For those not mathematically inclined, let's pretend you have a table, 'other_ table', which is a list of items, and another table, 'another_ table', which is a list of transaction numbers, and both tables form a many-to-many relationship, thus producing 'table1'. now let's pretend you wanted to know the id's in 'another_ table' which had items 1, 2, and 3. that's the query to do it.

    0 讨论(0)
提交回复
热议问题