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

[Release Notes] 20220325_v1 - Support Paypal & Patreon Donation button

[Release Notes] 20220325_v1 - Support Paypal & Patreon Donation button

[MSSQL] 產生特定條件的連續時間區段

[MSSQL] 產生特定條件的連續時間區段

[Web] 使用 OpenSSL 建立開發測試用途的自簽憑證(Self-Signed Certificate)和設置Domain Name

[Web] 使用 OpenSSL 建立開發測試用途的自簽憑證(Self-Signed Certificate)和設置Domain Name


Comments