Sql-Server

使用外鍵從映射表中選擇數據

  • April 9, 2021

我正在嘗試製作一個簡單的登錄系統,其中每個使用者都應該使用 MS SQL 根據他們的使用者 ID 從列表中顯示數據。在搜尋瞭如何做到最好之後,我遇到了映射(幾乎製作了一個包含 USR_ID 和 Element_ID 的 3d 表,當然都是外鍵)

CREATE TABLE [dbo].[Users] (
[USR_ID]        INT          IDENTITY (1, 1) NOT NULL,
[USR_UserName]  VARCHAR (50) NOT NULL,
[USR_Password]  VARCHAR (50) NOT NULL,
[USR_FirstName] VARCHAR (50) NOT NULL,
[USR_LastName]  VARCHAR (50) NOT NULL,
CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED ([USR_ID] ASC));

CREATE TABLE [dbo].[GameList] (
[GL_ID]          INT             IDENTITY (1, 1) NOT NULL,
[GL_Title]       NVARCHAR (MAX)  NOT NULL,
[GL_Genre]       NVARCHAR (MAX)  NOT NULL,
[GL_Plattform]   NVARCHAR (MAX)  NOT NULL,
[GL_ReleaseDate] DATETIME2 (7)   NOT NULL,
[GL_Price]       DECIMAL (18, 2) NOT NULL,
CONSTRAINT [PK_GameList] PRIMARY KEY CLUSTERED ([GL_ID] ASC));

CREATE TABLE [dbo].[UserGame] (
[UG_ID]  INT IDENTITY (1, 1) NOT NULL,
[USR_ID] INT NOT NULL,
[GL_ID]  INT NOT NULL,
CONSTRAINT [PK_UserGame] PRIMARY KEY CLUSTERED ([UG_ID] ASC),
CONSTRAINT [FK_USR_ID] FOREIGN KEY ([USR_ID]) REFERENCES [dbo].[Users] ([USR_ID]),
CONSTRAINT [FK_GL_ID] FOREIGN KEY ([GL_ID]) REFERENCES [dbo].[GameList] ([GL_ID]));

這就是我創建 3 個表的方式,而我的問題是如何從 dbo.GameList 中選擇所有具有相同 USR_ID 的遊戲 如果它就像使用 USR_ID 一個普通的外鍵,我可能會使用類似的東西

SELECT GameList.Title, GameList.Genre, GameList.Plattform, GameList.ReleaseDate, GameList.Price
FROM GameList
INNER JOIN Users ON GameList.USR_ID=Users.USR_ID;

但是因為這是我第一次使用映射,所以我一無所知。

提前致謝 !!

這是相同的

SELECT gl.Title, gl.Genre, gl.Plattform, gl.ReleaseDate, gl.Price
FROM GameList gl
INNER JOIN UserGame ug ON gl.GL_ID = ug.GL_ID
WHERE ug.USR_ID = 10;

只要您擁有 User_id,您就不需要更多,但如果您還需要來自 users 表的資訊

SELECT gl.Title, gl.Genre, gl.Plattform, gl.ReleaseDate, gl.Price
FROM GameList gl
INNER JOIN UserGame ug ON gl.GL_ID = ug.GL_ID
INNER JOIN Users u ON ug.USR_ID=u.USR_ID
WHERE ug.USR_ID = 10;

引用自:https://dba.stackexchange.com/questions/289528