king

mysql快速学习多表查询篇(八)

king Mysql 2018-05-21 1872浏览 0

MySQL 多表查询

1.在SELECT, UPDATE DELETE 语句中使用 Mysql JOIN 来联合多表查询。

JOIN 按照功能大致分为如下三类:

INNER JOIN(内连接,或等值连接):获取两个表中字段匹配关系的记录。
LEFT JOIN
(左连接):获取左表所有记录,即使右表没有对应匹配的记录。
RIGHT JOIN
(右连接):与 LEFT JOIN 相反,用于获取右表所有记录,即使左表没有对应匹配的记录。

| w3cschool_author |w3cschool_count |

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

| mahran | 20 |

| mahnaz | NULL |

| Jen | NULL |

| Gill | 20 |

| John Poul | 1 |

| Sanjay | 1 |

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

mysql> SELECT * fromw3cschool_tbl;

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

| w3cschool_id | w3cschool_title | w3cschool_author |submission_date |

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

| 1 | Learn PHP | John Poul |2007-05-24 |
| 2 | LearnMySQL | Abdul S | 2007-05-24 |
| 3 | JAVATutorial | Sanjay | 2007-05-06 |

连接以上两张表来读取w3cschool_tbl表中所有w3cschool_author字段在tcount_tbl表对应的w3cschool_count字段值:

mysql> SELECTa.w3cschool_id, a.w3cschool_author, b.w3cschool_count FROM w3cschool_tbl aINNER JOIN tcount_tbl b ON a.w3cschool_author = b.w3cschool_author;

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

| w3cschool_id | w3cschool_author | w3cschool_count |

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

| 1 | John Poul | 1 |

| 3 | Sanjay | 1 |

w3cschool_tbl 为左表,tcount_tbl 为右表,

mysql> SELECTa.w3cschool_id, a.w3cschool_author, b.w3cschool_count FROM w3cschool_tbl a LEFTJOIN tcount_tbl b ON a.w3cschool_author = b.w3cschool_author;

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

| w3cschool_id | w3cschool_author | w3cschool_count |

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

| 1 | John Poul | 1 |

| 2 | Abdul S | NULL |

| 3 | Sanjay | 1 |

左边的数据表w3cschool_tbl的所有选取的字段数据,即便在右侧表tcount_tbl中没有对应的w3cschool_author字段值Abdul S

MySQL NULL

IS NULL: 当列的值是NULL,此运算符返回true
IS NOT NULL:
当列的值不为NULL, 运算符返回true

NULL值与任何其它值的比较(即使是NULL)永远返回false

使用PHP脚本处理 NULL :

PHP脚本中你可以在 if...else 语句来处理变量是否为空,并生成相应的条件语句。


继续浏览有关 mysql 的文章
发表评论