我不能在标题部分更具体,但我想为我做一些有点复杂的事情。我以为我做到了,但事实证明它是错误的。
我有三张表如下:
ProjectTable
OfferTable
AccountTable
现在在一个查询中,我的目标是列出所有提供最多优惠的项目,并且在查询中我还想获得详细信息,例如所有者的用户名,提供者的用户名等。所以我不必再为每个项目查询。
这是我的破解查询,这是我第一次使用GROUP BY进行的实验,我可能还没有完成它。
SELECT Project.addDate,Project.idOwner ,Account.Username,Project.idProject,
Project.Price,COUNT(Project.idProject) as offercount
FROM Project
INNER JOIN Offer
ON Project.idProject= Offer.idProject
INNER JOIN Account
ON Account.idAccount = Project.idOwner
GROUP BY Project.addDate,Project.idOwner,
Account.Username,Project.idProject,Project.Price
ORDER BY addDate DESC
*:我写的不假思索,我只是想提出一些额外的信息,这要归功于Hosam Aly。
答案 0 :(得分:7)
尝试此操作(针对没有优惠的项目进行修改):
SELECT
Project.addDate,
Project.idOwner,
Account.Username,
Project.idProject,
Project.Price,
ISNULL(q.offercount, 0) AS offercount
FROM
(
SELECT
o.idProject,
COUNT(o.idProject) as offercount
FROM Offer o
GROUP BY o.idProject
) AS q
RIGHT JOIN Project ON Project.idProject = q.idProject
INNER JOIN Account ON Account.idAccount = Project.idOwner
ORDER BY addDate DESC
答案 1 :(得分:1)
我可能会稍微将查询切换为:
select p.addDate,
p.idOwner,
a.Username,
p.idProject,
p.price,
o.OfferCount
from project p
left join
(
select count(*) OfferCount, idproject
from offer
group by idproject
) o
on p.idproject = o.idproject
left join account a
on p.idowner = a.idaccount
这样,您将count
获取projectid
,而不是基于您所分组的所有其他字段。如果其他表中不存在LEFT JOIN
或其他ID,我也会使用projectid
,您仍会返回数据。
答案 2 :(得分:1)
你的问题有点模糊,但这里有一些指示:
ORDER BY offercount
。GROUP BY Project.idProject
在其他字段之前。内部查询可以在FROM
子句中,如其他答案所示,也可以直接在SELECT
子句中进行,如下所示:
SELECT Project.idProject,
(SELECT COUNT(Offer.idOffer)
FROM Offer
WHERE Offer.idProject = Project.idProject
) AS OfferCount
FROM Project