innert join與約束介紹


Posted by Leo Li on 2025-03-02

合併資料表

合併資料表有兩種做法:1.使用Where條件,進行合併資料表查詢 2.使用inner join進行合併資料表。一般來說Where比較偏向查詢方式,若要整合兩張表建議使用join語法來使用。
以上篇 資料表管理 建立完整資料庫(做關聯)的資料表進行示範。

搭配Where條件,進行合併資料表查詢

SELECT
    users.id,
    users.name,
    users.salary,
    teams.name AS 部門名稱
FROM users, teams
WHERE users.team_id = teams.id

使用inner join,進行

推薦使用inner join來合併資料表。

SELECT
    users.id,
  users.name,
  users.salary,
  teams.name AS 部門名稱
FROM users
INNER JOIN teams on users.team_id = teams.id

結果

約束constraint

INSERT INTO users (id, name, salary, team_id) VALUES
(4, '王多金', 66000, 2);

使用後出現『duplicate key value violates unique constraint "users_pkey"』錯誤 => 敘述這不是唯一值並constraint “users_pkey",資料表做出嚴謹不讓新增比數。

INSERT INTO users (name, salary, team_id) VALUES
('王多金', 66000, 3);

使用後出現『insert or update on table "users" violates foreign key constraint "users_team_id_fkey"』錯誤 => 敘述這外來鍵沒有這個id因此造成錯誤。


#SQL #where #Inner Join #constraint







Related Posts

Bootstrap5 如何安裝及檢測

Bootstrap5 如何安裝及檢測

Top issues on OWASP

Top issues on OWASP

利用 Cloud function 製作 GitHub Apps

利用 Cloud function 製作 GitHub Apps


Comments