MySql 連線查詢

2021-09-10 01:13:12 字數 2496 閱讀 3137

連線包括內連線和外連線。

通過連線運算子可以實現多個表查詢。

1 內連線查詢

mysql> select * from students;

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

| id | number | name | *** | age |

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

| 1 | 1111 | lily | w | 12 |

| 2 | 1112 | lucy | w | 11 |

| 3 | 1113 | lilei | m | 13 |

| 4 | 1114 | bird | null | 33 |

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

4 rows in set (0.00 sec)

mysql> select * from scores;

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

| id | number | chinese | english |

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

| 1 | 1111 | 99 | 87 |

| 2 | 1112 | 66 | 87 |

| 3 | 1113 | 55 | 100 |

| 4 | 1116 | 55 | 77 |

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

4 rows in set (0.00 sec)

mysql> select name,age,scores.chinese,scores.english from students inner join scores on students.number=scores.number;

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

| name | age | chinese | english |

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

| lily | 12 | 99 | 87 |

| lucy | 11 | 66 | 87 |

| lilei | 13 | 55 | 100 |

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

3 rows in set (0.00 sec)

2 外連線查詢

外連線又分為左外連線和右外連線。

left join: 會返還左邊表中所有資料和 與右表中與連線字段匹配的資料。  right join與之相似。

2.1 左連線示例

mysql> select name,age,scores.chinese,scores.english from students left outer join scores on students.number=scores.number;

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

| name | age | chinese | english |

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

| lily | 12 | 99 | 87 |

| lucy | 11 | 66 | 87 |

| lilei | 13 | 55 | 100 |

| bird | 33 | null | null |

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

4 rows in set (0.00 sec)

2.2 右連線示例

mysql> select name,age,scores.chinese from students right outer join scores on students.number=scores.number;

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

| name | age | chinese |

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

| lily | 12 | 99 |

| lucy | 11 | 66 |

| lilei | 13 | 55 |

| null | null | 55 |

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

4 rows in set (0.00 sec)

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...

mysql連線查詢on 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...