sql - various connections in sql

There are two tables

tablea 和 tableb

   

various connections

1. Cartesian product

SELECT * FROM TabA a,TabB b where a.id = b.id /* Cartesian product product */

The returned result is all records that satisfy a.id=b.id in the two tables. There are two records with the id of 1 in the b table, and one in the a table. It can be seen from the returned result that a record with the id of 1 is automatically filled in the a table.

The general Cartesian product SELECT * FROM TabA a, TabB returns 15 pieces of data. There are m records in table a and n records in table b, so the data returned by the general Cartesian product is m*n records. The combination between records is arbitrary.

2、inner join 

select * FROM TabA a INNER JOIN TabB b ON a.id=b.id /*inner join*/

The return result of inner join is the same as the Cartesian product.

 SELECT * FROM TabA a,TabB b where a.id = b.id /* Cartesian product product */

select * FROM TabA a INNER JOIN TabB b ON a.id=b.id /*inner join*/

Difference: execution mode The first statement combines the records of table a and table b, and then examines the records that meet the conditions and returns the records.

The second statement refers to the records in table a, go to table b one by one to find the matching records, if they match, connect them together, otherwise go to the next one in a

inner join is a special form of Cartesian product. In general, we choose inner join, and the efficiency of inner join is higher than that of Cartesian product.

3、left join

select * FROM TabA a LEFT JOIN TabB b ON a.id=b.id /*left join*/

All records in table a are returned, even if there is no match in table b.

4、right join

SELECT * FROM TabA a RIGHT JOIN TabB b ON a.id=b.id /*right join*/

All records in table b are returned, even if there are no records matching the conditions in table a.

5、full join 

In mysql, full join operation is not supported. We use

select * from TabA a left join TabB b on a.id = b.id
union
select *
from TabA a right join TabB b on a.id = b.id /* Returns all the rows of the left and right tables, which is equivalent to full join mysql does not support full join*/

full join: equal to the union of left join and right join

6. Query all records with the same id field and different name fields from the two tables

SELECT * FROM TabA a WHERE a.id in(SELECT id FROM TabB)
UNION
SELECT * FROM TabB b WHERE b.id in(SELECT id FROM TabA) ORDER BY id /*UNION 去重 UNINSTALL 不去重*/

 

SELECT * FROM TabA a WHERE EXISTS (SELECT id FROM TabB b WHERE a.id=b.id)
UNION ALL
SELECT * FROM TabB b WHERE EXISTS (SELECT id FROM TabA a WHERE a.id=b.id)

 

The performance of the latter statement is better than the first.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325303981&siteId=291194637
SQL