join three tables for specific result

后端 未结 2 1583
南方客
南方客 2021-01-27 14:49

I have three tables:

Table 1 Users:

+----------+------------+------------+-------------------+
| ID [PK]  |  username  |           


        
相关标签:
2条回答
  • 2021-01-27 15:39

    A LEFT JOIN will always return all records from the table on the left of the join, and only values from those records which match the join criteria from tables on the right of the join.

    To only return records for which there join criteria is validated for every record, you should use an INNER JOIN, i.e.:

    SELECT * 
    FROM 
        CR_AR C 
        INNER JOIN STRUCT S ON S.STRUCTURE = C.STRUCT 
        INNER JOIN USERS U ON U.USER_STRUCT = S.STRUCTURE
    
    0 讨论(0)
  • 2021-01-27 15:49

    Your data example talks about foreign keys, but table STRUCT does not contain ADM, but IDM. So something is inconsistent there.

    If you do not want all the rows to be returned, you should not use outer joins. Use inner joins instead.

    Here is my test, based on your example, with a couple of suggested queries you might find useful:

    create table users (
        id int,
        username varchar(10),
        pwd varchar(10),
        user_struct varchar(3)
    )
    
    create table cr_ar (
        id int,
        num int,
        struct varchar(3)
    )
    
    create table struct (
        structure varchar(3),
        description varchar(10)
    )
    
    insert into users values (1, 'sam', 123, 'CIF')
    insert into users values (2, 'jack', 123, 'ADM')
    insert into users values (3, 'jamal', 123, 'SDT')
    
    insert into cr_ar values (1, 11, 'CIF')
    insert into cr_ar values (2, 22, 'ADM')
    insert into cr_ar values (3, 33, 'SDT')
    
    insert into struct values ('CIF', null)
    insert into struct values ('IDM', null)
    insert into struct values ('SDT', null)
    
    -- your query
    SELECT * FROM CR_AR AS C 
    LEFT JOIN STRUCT AS S ON S.STRUCTURE = C.STRUCT 
    LEFT JOIN USERS AS U ON U.USER_STRUCT = S.STRUCTURE
    
    -- no outer joins
    SELECT * FROM CR_AR AS C 
    JOIN STRUCT AS S ON S.STRUCTURE = C.STRUCT 
    JOIN USERS AS U ON U.USER_STRUCT = S.STRUCTURE
    
    -- alternative with outer joins (showing struct ADM does not exist)
    SELECT * FROM CR_AR AS C 
    LEFT JOIN USERS AS U ON U.USER_STRUCT = C.struct
    LEFT JOIN struct AS s ON s.structure = c.struct
    
    0 讨论(0)
提交回复
热议问题