美文网首页
2020-04-01

2020-04-01

作者: DUYAN_bc77 | 来源:发表于2020-04-01 16:20 被阅读0次

    连接两表

    Create table Person (PersonId int, FirstName varchar(255), LastName varchar(255))
    Create table Address (AddressId int, PersonId int, City varchar(255), State varchar(255))
    Truncate table Person
    insert into Person (PersonId, LastName, FirstName) values ('1', 'Wang', 'Allen')
    Truncate table Address
    insert into Address (AddressId, PersonId, City, State) values ('1', '2', 'New York City', 'New York')
    

    SOLUTION

    Select Person.FirstName, Person.LastName, Address.City, Address.State
    From Person
    Left join Address
    On Person.PersonId=Address.PersonId
    

    输入

    {"headers": {"Person": ["PersonId", "LastName", "FirstName"], "Address": ["AddressId", "PersonId", "City", "State"]}, "rows": {"Person": [[1, "Wang", "Allen"]], "Address": [[1, 2, "New York City", "New York"]]}}
    

    输出

    {"headers": ["FirstName", "LastName", "City", "State"], "values": [["Allen", "Wang", null, null]]}
    

    解题思路
    SQL 连接类型
    SQL 中有多种不同的连接:

    内连接(INNER JOIN):只返回两张表匹配的记录,这叫内连接(inner join)

    {"headers": ["FirstName", "LastName", "City", "State"], "values": []}
    

    左连接(LEFT JOIN):返回匹配的记录,以及表 A 多余的记录,这叫左连接

    右连接(RIGHT JOIN):返回匹配的记录,以及表 B 多余的记录,这叫右连接。

    {"headers": ["FirstName", "LastName", "City", "State"], "values": [[null, null, "New York City", "New York"]]}
    

    全连接(FULL JOIN):返回匹配的记录,以及表 A 和表 B 各自的多余记录,这叫全连接(full join)。

    笛卡尔连接(CARTESIAN JOIN):返回两个或者更多的表中记录集的笛卡尔积。

    image.png

    这四种连接,又可以分成两大类:内连接(inner join)表示只包含匹配的记录,外连接(outer join)表示还包含不匹配的记录。所以,左连接、右连接、全连接都属于外连接。

    四种连接的 SQL 语句

    SELECT * FROM A  
    INNER JOIN B ON A.book_id=B.book_id;
    
    SELECT * FROM A  
    LEFT JOIN B ON A.book_id=B.book_id;
    
    SELECT * FROM A  
    RIGHT JOIN B ON A.book_id=B.book_id;
    
    SELECT * FROM A  
    FULL JOIN B ON A.book_id=B.book_id;
    

    WHERE条件从句,对记录进行筛选

    SELECT * FROM A
    LEFT JOIN B
    ON A.book_id=B.book_id
    WHERE B.id IS null;
    

    只返回A里面不匹配B的记录

    https://www.ruanyifeng.com/blog/2019/01/table-join.html

    相关文章

      网友评论

          本文标题:2020-04-01

          本文链接:https://www.haomeiwen.com/subject/jcdauhtx.html