MySQL 使用篇 連線查詢

2021-10-23 19:03:06 字數 2817 閱讀 9456

現有t1t2兩張表

mysql> select * from t1;

+------+------+

| m1 | n1 |

+------+------+

| 1 | a |

| 2 | b |

| 3 | c |

+------+------+

3 rows in set (0.00 sec)

mysql> select * from t2;

+------+------+

| m2 | n2 |

+------+------+

| 2 | b |

| 3 | c |

| 4 | d |

+------+------+

3 rows in set (0.00 sec)

mysql>連線

連線查詢,如果不做限制,就是笛卡爾積組合

笛卡爾積就是兩兩組合。

比如(1,2,3)(a,b,c)

組合後就是 1a 1b 1c 2a 2b 2c 3a 3b 3c

select * from t1, t2;

+------+------+------+------+

| m1 | n1 | m2 | n2 |

+------+------+------+------+

| 1 | a | 2 | b |

| 2 | b | 2 | b |

| 3 | c | 2 | b |

| 1 | a | 3 | c |

| 2 | b | 3 | c |

| 3 | c | 3 | c |

| 1 | a | 4 | d |

| 2 | b | 4 | d |

| 3 | c | 4 | d |

+------+------+------+------+

# 下面的方式等價

select t1.m1, t1.n1, t2.m2, t2.n2 from t1, t2;

select m1, n1, m2, n2 from t1, t2;

select t1.*, t2.* from t1, t2;

# 左(外)連線的語法

select * from t1 left [outer] join t2 on 連線條件 [where 普通過濾條件];

# 右(外)連線的語法

select * from t1 right [outer] join t2 on 連線條件 [where 普通過濾條件];

# 內連線的語法

select * from t1 [inner | cross] join t2 [on 連線條件] [where 普通過濾條件];

# mysql中,以下寫法等價

select * from t1 join t2;

select * from t1 inner join t2;

select * from t1 cross join t2;

例:

mysql> select * from t1 inner join t2 on t1.m1 = t2.m2;

+------+------+------+------+

| m1 | n1 | m2 | n2 |

+------+------+------+------+

| 2 | b | 2 | b |

| 3 | c | 3 | c |

+------+------+------+------+

2 rows in set (0.00 sec)

mysql> select * from t1 left join t2 on t1.m1 = t2.m2;

+------+------+------+------+

| m1 | n1 | m2 | n2 |

+------+------+------+------+

| 2 | b | 2 | b |

| 3 | c | 3 | c |

| 1 | a | null | null |

+------+------+------+------+

3 rows in set (0.00 sec)

mysql> select * from t1 right join t2 on t1.m1 = t2.m2;

+------+------+------+------+

| m1 | n1 | m2 | n2 |

+------+------+------+------+

| 2 | b | 2 | b |

| 3 | c | 3 | c |

| null | null | 4 | d |

+------+------+------+------+

3 rows in set (0.00 sec)

MySQL 使用篇 組合查詢

組合查詢,也叫合併查詢,就是將多個sql語句的查詢結果集合並為乙個大的結果集。比如有如下兩個sql語句 mysql select m1 from t1 where m1 2 m1 1 1 row in set 0.00 sec mysql select m1 from t1 where m1 2 m...

mysql連線查詢例項 MySQL連線查詢例項詳解

建立表suppliers create table suppliers s id int not null auto increment,s name char 50 not null,s city char 50 null,s zip char 10 null,s call char 50 not...

mysql連線查詢例項 MySQL連線查詢例項詳解

建立表suppliers create table suppliers s id int not null auto increment,s name char 50 not null,s city char 50 null,s zip char 10 null,s call char 50 not...