查询:
SELECT
ei.ItemIdn as ItemIdn,
ei.UserIdn as UserIdn,
ifnull(cb.BestPrice,0) as BestPrice,
cv.CountShow as CountShow,
cb.CountBids as CountBids,
ifnull(r.CountReactivation,0) as CountReactivation
FROM items ei
left join (
SELECT count(*) as CountShow, ItemIdn
FROM CountViewes
WHERE ItemIdn = ItemIdn) as cv on cv.ItemIdn = ei.ItemIdn
left join (
SELECT count(*) as CountBids, Max(Bid) as BestPrice, ItemIdn
FROM CountBids
WHERE ItemIdn = ItemIdn) as cb on cb.ItemIdn = ei.ItemIdn
left join (SELECT count(*) as CountReactivation, ItemIdn
FROM Reactivation
WHERE ItemIdn = ItemIdn) as r on r.ItemIdn = ei.ItemIdn
WHERE ei.UserIdn = '0000'
LIMIT 0, 25
问题:如果我使用left join
我只获得一行(请参阅sqlfiddle),但表items
有4行
请告诉我,如何使用left join
计算行数和最大值?
答案 0 :(得分:0)
您可以通过在子查询中进行聚合来解决此问题:
left join (SELECT ItemIdn, count(*) as CountBids, Max(Bid) as BestPrice
FROM CountBids
GROUP BY ItemIdn
) cb
on cb.ItemIdn = ei.ItemIdn
编辑:
您需要使用ItemIdn = ItemIdn
替换每个子查询中的group by ItemIdn
。您还需要从外部查询中删除count()
:
SELECT
ei.ItemIdn as ItemIdn,
ei.UserIdn as UserIdn,
ifnull(cb.BestPrice,0) as BestPrice,
cv.CountShow as CountShow,
cb.CountBids as CountBids,
ifnull(r.CountReactivation,0) as CountReactivation
FROM items ei
left join (
SELECT count(*) as CountShow, ItemIdn
FROM CountViewes
group by ItemIdn) as cv on cv.ItemIdn = ei.ItemIdn
left join (
SELECT count(*) as CountBids, Max(Bid) as BestPrice, ItemIdn
FROM CountBids cb
group by ItemIdn ) as cb on cb.ItemIdn = ei.ItemIdn
left join (SELECT count(*) as CountReactivation, ItemIdn
FROM Reactivation
group by ItemIdn) as r on r.ItemIdn = ei.ItemIdn
WHERE ei.UserIdn = '0000' ;
如果您打算在外层进行聚合,请使用sum()
,而不是count()
。
答案 1 :(得分:0)
这应该有效:
SELECT
ei.DateStart as DateStart,
ei.DateEnd as DateEnd,
ei.ItemIdn as ItemIdn,
ei.Title as Title,
ei.AuctionMinCost as AuctionMinCost,
ei.Priority as Priority,
ei.PriceBuyOnly as PriceBuyOnly,
ei.ItemCount as ItemCount,
ifnull(MAX(cb.Bid),0) as BestPrice,
count(cb.ItemIdn) as CountBids
FROM items ei
LEFT JOIN CountBids cb ON cb.ItemIdn = ei.ItemIdn
WHERE ei.User = '0'
GROUP BY ei.ItemIdn
Order by ei.DateStart ASC
LIMIT 0, 25
更新:
当连接多个表并需要对每个表进行分组时,您需要使用子查询。每个子查询都需要进行自己的分组,不要在主查询中使用聚合。
SELECT
ei.ItemIdn as ItemIdn,
ei.UserIdn as UserIdn,
ifnull(cb.BestPrice,0) as BestPrice,
cv.CountShow as CountShow,
cb.CountBids as CountBids,
ifnull(r.CountReactivation,0) as CountReactivation
FROM items ei
left join (
SELECT count(*) as CountShow, ItemIdn
FROM CountViewes
GROUP BY ItemIdn) as cv on cv.ItemIdn = ei.ItemIdn
left join (
SELECT count(*) as CountBids, Max(Bid) as BestPrice, ItemIdn
FROM CountBids
GROUP BY ItemIdn) as cb on cb.ItemIdn = ei.ItemIdn
left join (SELECT count(*) as CountReactivation, ItemIdn
FROM Reactivation
GROUP BY ItemIdn) as r on r.ItemIdn = ei.ItemIdn
WHERE ei.UserIdn = '0000'
LIMIT 0, 25
顺便说一下,查询中不需要WHERE ItemIdn = ItemIdn
。如果查询没有条件,请忽略WHERE
子句。