帮助解决复杂的 SELECT 查询
我有这个 SELECT 查询:
SELECT Auctions.ID, Users.Balance, Users.FreeBids,
COUNT(CASE WHEN Bids.Burned=0 AND Auctions.Closed=0 THEN 1 END) AS 'ActiveBids',
COUNT(CASE WHEN Bids.Burned=1 AND Auctions.Closed=0 THEN 1 END) AS 'BurnedBids'
FROM (Users INNER JOIN Bids ON Users.ID=Bids.BidderID)
INNER JOIN Auctions
ON Bids.AuctionID=Auctions.ID
WHERE Users.ID=@UserID
GROUP BY Users.Balance, Users.FreeBids, Auctions.ID
我的问题是,如果在 Bid 表中找不到 UserID,它不会返回任何行。
我知道这与我的问题有关
(Users INNER JOIN Bids ON Users.ID=Bids.BidderID)
,但我不知道如何让它返回,即使用户不在出价表上。
I have this SELECT query:
SELECT Auctions.ID, Users.Balance, Users.FreeBids,
COUNT(CASE WHEN Bids.Burned=0 AND Auctions.Closed=0 THEN 1 END) AS 'ActiveBids',
COUNT(CASE WHEN Bids.Burned=1 AND Auctions.Closed=0 THEN 1 END) AS 'BurnedBids'
FROM (Users INNER JOIN Bids ON Users.ID=Bids.BidderID)
INNER JOIN Auctions
ON Bids.AuctionID=Auctions.ID
WHERE Users.ID=@UserID
GROUP BY Users.Balance, Users.FreeBids, Auctions.ID
My problam is that it returns no rows if the UserID cant be found on the Bids table.
I know it's something that has to do with my
(Users INNER JOIN Bids ON Users.ID=Bids.BidderID)
But i dont know how to make it return even if the user is no on the Bids table.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在执行 INNER JOIN,仅当连接两侧都有结果时才返回行。要获得您想要的结果,请像这样更改 WHERE 子句:
您可能还需要更改 SELECT 语句以处理 Bids.Burned 为 NULL。
如果即使没有匹配的拍卖您也想返回行,那么您必须对查询进行一些更深层次的更改。
You're doing an INNER JOIN, which only returns rows if there are results on both sides of the join. To get what you want, change your WHERE clause like this:
You may also have to change your SELECT statement to handle Bids.Burned being NULL.
If you want to return rows even if there's no matching Auction, then you'll have to make some deeper changes to your query.
那么
INNER JOIN Bids/Auctions
可能应该是左外连接。按照您编写的方式,您正在过滤用户,以便仅显示出价和拍卖中的用户。Then
INNER JOIN Bids/Auctions
should probably be left outer joins. The way you've written it, you're filtering users so that only those in bids and auctions appear.左连接是简单的答案,但如果您担心性能,我会考虑稍微重写一下。一方面,分组中列的顺序对性能很重要(尽管它通常不会改变结果)。通常,您希望按首先索引的列进行分组。
另外,可以重写此查询以仅包含一个分组依据,这可能会加快速度。
尝试一下:
如果您不熟悉
with UserBids as...
,它称为 CTE(通用表表达式),基本上是一种制作一次性使用视图的方法,以及构建查询的好方法。Left join is the simple answer, but if you're worried about performance I'd consider re-writing it a little bit. For one thing, the order of the columns in the group by matters to performance (although it often doesn't change the results). Generally, you want to group by a column that's indexed first.
Also, it's possible to re-write this query to only have one group by, which will probably speed things up.
Try this out:
If you're not familiar with the
with UserBids as...
, it's called a CTE (common table expression), and is basically a way to make a one-time use view, and a nice way to structure your queries.