我正在构建asp.net mvc app,我在多个表上编写SQL存储过程时遇到了麻烦。
我有7个不同的表,彼此相互连接。
Customer
Id
Name
CustomerBook
Id
CustomerId
BookId
Book
Id
Name
BookType
Id
BookId
TypeId
Type
Id
Name
BookCategory
BookId
CategoryId
Category
Id
Name
它看起来像那样。
CustomerBook.CustomerId = Customer.Id
CustomerBook.BookId = Book.Id
BookCategory.BookId = Book.Id
BookCategory.CategoryId = Category.Id
BookType.BookId = Book.Id
BookType.TypeId = Book.Id
如果我没弄错的话。
我现在要做的是编写存储过程,以获取并显示特定用户“购买”的所有书籍。
我想展示:
Book name
Book type
Book category
...为当前登录会话的每个用户。
后来我想把数据输入控制器......但这是另一天的问题。
由于我对程序很新,只知道一点SQL,我真的很感谢你的帮助!
这是我到目前为止所尝试的:
CREATE PROCEDURE [dbo].[getBookByCustomerId]
@Id int
AS
BEGIN
SET NOCOUNT ON;
SELECT * FROM [Customer] WHERE Id = @id
END
现在我卡住了......
答案 0 :(得分:2)
这样的事情应该这样做:
CREATE PROCEDURE [dbo].[getBookByCustomerId]
@Id INT
AS
BEGIN
SET NOCOUNT ON;
SELECT
B.Id,
B.Name,
T.Name,
C.Name
FROM Book B
INNER JOIN CustomerBook CB ON B.Id = CB.BookId
INNER JOIN BookType BT ON B.ID = BT.BookID
INNER JOIN Type T ON BT.TypeID = T.ID
INNER JOIN BookCategory BC ON B.BookId = BC.BookId
INNER JOIN Category C ON BC.CategoryId = C.CategoryId
WHERE CB.CustomerID = @Id;
END;
它将获取BookID和Name,其中customerID等于传入的值。
INNER JOIN只会获取两个表中的记录,here是了解联接的好帖子。
答案 1 :(得分:-1)
此参数@Id代表客户ID。
CREATE PROCEDURE [dbo].[getBookByCustomerId]
@Id int
AS
BEGIN
SET NOCOUNT ON;
SELECT
B.Id, B.Name, T.Name, C.Name
FROM
Customer C
INNER JOIN
CustomerBook CB ON C.Id = CB.CustomerId
INNER JOIN
Book B ON B.Id = CB.Id
INNER JOIN
BookType BT ON B.Id = BT.BookId
INNER JOIN
Type T ON BT.TypeId = T.Id
INNERJOIN
BookCategory BC ON
BC.BookId = B.BookId
INNER JOIN
Category CT on CT.Id = BC.CategoryId
WHERE
C.Id = @Id
END