Big data-SQL join

SQL JOIN

Join clause is used to combine records from two or more tables in database.

Optimization:

on is better than where. on clause (A left join B on …) determines how to retrieve rows from table B. where will be used after this period. So try to use where less and satisfy condition on.
Pass:

1
2
3
4
5
6
7
8
9
10
11
12
mysql> SELECT * FROM product LEFT JOIN product_details
ON (product.id = product_details.id)
AND product_details.id=2;
+----+--------+------+--------+-------+
| id | amount | id | weight | exist |
+----+--------+------+--------+-------+
| 1 | 100 | NULL | NULL | NULL |
| 2 | 200 | 2 | 22 | 0 |
| 3 | 300 | NULL | NULL | NULL |
| 4 | 400 | NULL | NULL | NULL |
+----+--------+------+--------+-------+
4 rows in set (0.00 sec)

Great:

1
2
3
4
5
6
7
8
9
mysql> SELECT * FROM product LEFT JOIN product_details
ON (product.id = product_details.id)
WHERE product_details.id=2;
+----+--------+----+--------+-------+
| id | amount | id | weight | exist |
+----+--------+----+--------+-------+
| 2 | 200 | 2 | 22 | 0 |
+----+--------+----+--------+-------+
1 row in set (0.01 sec)

Pass:

1
insert into t1(a1) select b1 from t2 where not exists(select 1 from t1 where t1.id = t2.r_id);

Great:

1
2
3
4
insert into t1(a1)  
select b1 from t2
left join (select distinct t1.id from t1 ) t1 on t1.id = t2.r_id
where t1.id is null;

Reference:

https://blog.csdn.net/u012861978/article/details/52203818