大家好我需要通过告诉用户进行搜索,按名称或价格进行搜索
SELECT
BID.BiddingPrice, BID.Date, Item.Name
FROM
BID
INNER JOIN
Buyer ON BID.BuyerID = Buyer.BuyerID
INNER JOIN
Member ON Buyer.MemberID = Member.MemberID
INNER JOIN
Auction ON BID.AuctionID = Auction.AuctionID
INNER JOIN
Item ON Auction.ItemID = Item.ItemID
WHERE
(Auction.Status = 'Expired')
AND (BID.Date BETWEEN @from AND @to)
OR (BID.Status = 'Available')
OR (Member.Username = @username)
OR (BID.BiddingPrice = @price)
OR (Item.Name = @name)
答案 0 :(得分:0)
我已经强调了我认为实现您正在寻找的结果所需的更改。您需要根据用户提供的内容传递price或name的值,并为其他值传递NULL。例如,name ='Ron',price = NULL。
SELECT BID.BiddingPrice, BID.Date, Item.Name
FROM BID INNER JOIN
Buyer ON BID.BuyerID = Buyer.BuyerID INNER JOIN
Member ON Buyer.MemberID = Member.MemberID INNER JOIN
Auction ON BID.AuctionID = Auction.AuctionID INNER JOIN
Item ON Auction.ItemID = Item.ItemID
WHERE (Auction.Status = 'Expired') AND (BID.Date BETWEEN @from AND @to) **AND**
(BID.Status = 'Available') **AND**
(Member.Username = @username) **AND**
**CASE WHEN @Price IS NOT NULL THEN
(BID.BiddingPrice = @price) ELSE
(Item.Name = @name)
END**
答案 1 :(得分:0)
SELECT BID.BiddingPrice, BID.Date, Item.Name
FROM BID
INNER JOIN Buyer ON BID.BuyerID = Buyer.BuyerID
INNER JOIN Member ON Buyer.MemberID = Member.MemberID
INNER JOIN Auction ON BID.AuctionID = Auction.AuctionID
INNER JOIN Item ON Auction.ItemID = Item.ItemID
WHERE
Auction.Status = 'Expired'
AND (BID.Date BETWEEN @from AND @to)
OR BID.Status = 'Available'
OR Member.Username = @username
OR(
(Item.Name = @name OR @name is null)
OR (BID.BiddingPrice = @price OR @price is null)
)
如果任何@parameter可以为null,那么你应该创建你的where子句,如:
WHERE
Auction.Status = 'Expired'
AND (BID.Date>= @from OR @from is null)
AND (BID.Date<= @to OR @to IS NULL)
OR BID.Status = 'Available'
OR (Member.Username = @username OR @username is null)
OR(
(Item.Name = @name OR @name is null)
OR (BID.BiddingPrice = @price OR @price is null)
)
答案 2 :(得分:0)
虽然可以通过巧妙地“打开和关闭”WHERE子句的某些部分(如其他答案所示)在静态查询中完成此操作,但请注意这样做的潜在性能影响 - DBMS可能无法制定最佳查询计划。
这是dynamic SQL可能更合适的其中一种情况。使用动态SQL并不意味着你应该停止使用绑定参数!