我有一个项目,用户可以在其中插入拍卖,招标和广告。他们还可以参加拍卖和招标。 我在设计和连接数据库及连接时遇到了麻烦。 我的数据库中的“关系”中存在循环。
我有六个表:
user(user_id,firstName,LastName,...)
<-所有用户。
Order(order_id,user_id,OrderName,Desc,Amount,OrderType,...)
<-所有广告。
Auction(auction_id,order_id,start_date,block_amount,min_increase,end_date,...)
Tender(tender_id,order_id,tender_base_amount,tender_start_date,tender_expire_date,...)
AuctionOffer(offer_auction_id,auction_id,user_id,auction_amount_offer,Date)
TenderOffer(tender_offer_id,tender_id,user_id,auction_amount_offer,Date)
我的关系:
您对解决此问题有何建议?
答案 0 :(得分:1)
我看不到任何循环。所有外键都指向User
。
CREATE TABLE [User] (
[user_id] INT NOT NULL PRIMARY KEY,,
[user_name] VARCHAR(50),
[first_name] VARCHAR(50),
[last_name] VARCHAR(50)
);
CREATE TABLE [Order] (
[order_id] INT NOT NULL PRIMARY KEY,
[user_id] INT REFERENCES [User] ( [user_id] )
[order_name] VARCHAR(50)
);
CREATE TABLE [Auction] (
[auction_id] INT NOT NULL PRIMARY KEY,
[order_id] INT REFERENCES [Order] ( [order_id] )
--,...
);
CREATE TABLE [AuctionOffer] (
[offer_auction_id] INT NOT NULL PRIMARY KEY,
[auction_id] INT REFERENCES [Auction] ( [auction_id] ),
[user_id] INT REFERENCES [User] ( [user_id] )
--,...
);
CREATE TABLE [Tender] (
[tender_id] INT NOT NULL PRIMARY KEY,
[order_id] INT REFERENCES [Order] ( [order_id] )
--,...
);
CREATE TABLE [TenderOffer] (
[tender_offer_id] INT NOT NULL PRIMARY KEY,
[tender_id] INT REFERENCES [Tender] ( [tender_id] ),
[user_id] INT REFERENCES [User] ( [user_id] )
---,...
);
必须首先创建 Users
,然后创建Orders
。之后,Tenders
和TenderOffers
或Auctions
和AuctionOffers
。
要在查询中联接表:
SELECT
a.[auction_id],
o.[order_id], o.[order_name], ou.[user_name] as [creator]
FROM [Auction] a
INNER JOIN [Order] o ON o.[order_id] = a.[order_id]
INNER JOIN [User] ou ON ou.[user_id] = o.[user_id]
;
SELECT
aou.[user_name] as [bidder], ao.[created_date], ao.[auction_amount_offer]
FROM [AuctionOffer] ao
INNER JOIN [User] aou ON aou.[user_id] = ao.[user_id]
WHERE ao.[auction_id] = ?
ORDER BY ao.[Date] DESC
;
或组合:
SELECT
a.[auction_id],
o.[order_id], o.[order_name], ou.[user_name] AS [creator],
aou.[user_name] AS [bidder], ao.[created_date], ao.[auction_amount_offer]
FROM [Auction] a
INNER JOIN [Order] o ON o.[order_id] = a.[order_id]
INNER JOIN [User] ou ON ou.[user_id] = o.[user_id]
LEFT JOIN [AuctionOffer] ao ON ao.[auction_id] = a.[auction_id] AND ao.[deleted_at] IS NULL
LEFT JOIN [User] aou ON aou.[user_id] = ao.[user_id]
ORDER BY a.[start_date], a.[start_time] a.[auction_id], ao.[created_at]
请注意,[User]
有两个实例,但是别名不同。还有两列用于[User].[user_name]
,但用于不同的表别名。
答案 1 :(得分:0)
我同意马库斯的观点,我没有看到任何M:M(多对多)关系,1个用户可以有很多拍卖要价,投标要约和订单(1:M),1个订单可以有很多拍卖和招标( 1:M);并且1个拍卖或投标可以有许多拍卖要约或要约(1:M)。 TenderOffers和AuctionOffers表是解决任何M:M关系的“连接表”。