我使用ASP.NET Membership,最重要的是我添加了一些与用户有一对多关系的表。
一个用户有很多钢笔,笔记本等。
我正在编写自定义成员资格提供程序并修改了select查询以检索有关用户的所有信息以及用户拥有的笔数和“工具”总数,但查询显然会执行灾难性的操作。 无论如何得到那些信息? 这就是我的尝试:
SET STATISTICS TIME ON
SELECT m.Email, m.PasswordQuestion, m.IsApproved, m.CreateDate, m.LastLoginDate,
u.LastActivityDate, m.LastPasswordChangedDate, u.UserId, m.IsLockedOut,
m.LastLockoutDate, CAST(m.Comment as nvarchar(max)) as Comment,
COUNT(DISTINCT cl.Id) AS NumberOfPens,
COUNT(DISTINCT cf.Id)+
COUNT(DISTINCT cm.Id) +
COUNT(DISTINCT ce.Id) +
COUNT(DISTINCT cl.Id) +
COUNT(DISTINCT cp.Id) +
COUNT(DISTINCT csl.Id)+
COUNT(DISTINCT cs.Id) +
COUNT(DISTINCT cshl.Id) AS NumberOfTools
FROM aspnet_Membership AS m
INNER JOIN aspnet_Users AS u ON m.UserId = u.UserId
INNER JOIN Pens AS cf ON u.UserId = cf.Owner
INNER JOIN Notebooks AS cm ON u.UserId = cm.Owner
INNER JOIN Rulers AS ce ON u.UserId = ce.Owner
INNER JOIN Calculators AS cl ON u.UserId = cl.Owner
CROSS JOIN aspnet_Applications AS a
GROUP BY u.UserId, m.Email, m.PasswordQuestion, m.IsApproved,
m.CreateDate, m.LastLoginDate, u.LastActivityDate,
m.LastPasswordChangedDate, m.IsLockedOut, m.LastLockoutDate,
CAST(m.Comment as nvarchar(max))
SET STATISTICS TIME OFF
91位用户9分11秒!
答案 0 :(得分:3)
SELECT m.Email, m.PasswordQuestion, m.IsApproved, m.CreateDate, m.LastLoginDate,
u.LastActivityDate, m.LastPasswordChangedDate, u.UserId, m.IsLockedOut,
m.LastLockoutDate, CAST(m.Comment as nvarchar(max)) as Comment,
penCount,
notebookCount + rulerCount + calculatorCount AS toolCount
FROM aspnet_Membership m
JOIN aspnet_Users u
ON u.userId = m.userId
CROSS APPLY
(
SELECT COUNT(*)
FROM pens
WHERE owner = u.UserId
) p (penCount)
CROSS APPLY
(
SELECT COUNT(*)
FROM notebooks
WHERE owner = u.UserId
) n (notebookCount)
CROSS APPLY
(
SELECT COUNT(*)
FROM rulers
WHERE owner = u.UserId
) r (rulerCount)
CROSS APPLY
(
SELECT COUNT(*)
FROM calculators
WHERE owner = u.UserId
) c (calculatorCount)
答案 1 :(得分:2)
快速点击,最后取出cross join
- 您没有使用它,只是将结果倍增并减慢速度。
此外,您可以在加入之前执行计数,这将保存group by
并允许RDBMS并行化查询,如下所示:
SELECT
m.Email,
m.PasswordQuestion,
m.IsApproved,
m.CreateDate,
m.LastLoginDate,
u.LastActivityDate,
m.LastPasswordChangedDate,
u.UserId,
m.IsLockedOut,
m.LastLockoutDate,
CAST(m.Comment as nvarchar(max)) as Comment,
PenCount AS NumberOfPens,
PenCount + NotebookCount + RulerCount + CalculatorCount AS NumberOfTools
FROM
aspnet_Membership AS m
INNER JOIN aspnet_Users AS u ON
m.UserId = u.UserId
INNER JOIN (select owner, count(1) as PenCount from Pens group by owner) AS cf ON
u.UserId = cf.Owner
INNER JOIN (select owner, count(1) as NotebookCount from Notebooks group by owner) AS cm ON
u.UserId = cm.Owner
INNER JOIN (select owner, count(1) as RulerCount from Rulers group by owner) AS ce ON
u.UserId = ce.Owner
INNER JOIN (select owner, count(1) as CalculatorCount from Calculators group by owner) AS cl ON
u.UserId = cl.Owner
请注意,如果用户可能没有所有工具,则您需要LEFT
加入以代替inner
加入,然后将所有{{}包裹起来{1}} *Count
列。