父表:
adverts
- id
子表:
advertsitems
- id
- advertid
- price
- quantity
我正在尝试根据advertid
计算数量,但不知怎的,我无法让它发挥作用。这就是我所拥有的:
SELECT adverts.title AS adtitle,
adverts.id AS adid,
adverts.image AS image,
description,
price,
shipping,
customs,
createdate
FROM adverts
LEFT JOIN advertsitems
ON adverts.id = advertsitems.advertid
GROUP BY adid
ORDER BY adid DESC
我尝试添加COUNT(advertsitems.quantity),但它不算数。
答案 0 :(得分:0)
您在没有聚合的情况下从price
提取advertsitems
字段。这从任意行中提取价格。以下查询将此替换为min()
。您可能需要max()
或avg()
。
我假设select
中除价格之外的所有列都来自adverts
表。它们以适当的别名作为前缀。
最后,我认为你想要的是sum(quantity)
,而不是count(quantity)
。
SELECT a.title AS adtitle,
a.id AS adid,
a.image AS image,
a.description,
sum(ai.quantity) as quantity
min(price) as LowestPrice,
a.shipping,
a.customs,
a.createdate
FROM adverts a LEFT JOIN
advertsitems ai
ON a.id = ai.advertid
GROUP BY a.id
ORDER BY a.id DESC