重新瞭解數據庫——聯表查詢和自連接

聯表查詢join

聯表查詢分爲Inner join、left join、right join

left join左連接:以左表爲主。結果會將左表所有的查詢信息列出,而右表只列出ON後條件與左表滿足的部分。

right join左連接:以右表爲主。結果會將右表所有的查詢信息列出,而左表只列出ON後條件與右表滿足的部分。

 

查詢學生的學號,姓名和成績從student學生表和result成績表

Inner join:

select s.id,name,score
from student as s
inner join result as r
where s.id = r.id;

left join:

select s.id,name,score
from student as s
left join result as r
where s.id = r.id;

right join:

select s.id,name,score
from student as s
right join result as r
where s.id = r.id;

 

自連接

  • 自連接是連接的一種用法,但並不是連接的一種類型,因爲他的本質是把一張表當成兩張表來使用。
  • mysql有時在信息查詢時需要進行對自身連接,所以我們需要爲表來定義別名。

查詢父子信息:把一張表看爲兩個一模一樣的表,然後就可以對錶進行其他操作了。

select a.categoryName as '父列',b.categoryName as '子列'
from category as a,category as b
where a.categoryid = b.pid;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章