我试图创建一个MYSQL查询来选择最新的10个广告记录,其中图像的数量大于0.问题是我在'where子句'中得到错误“未知列'num_photos'”因为where语句在计数之前执行。我将如何重写这个mysql查询以解决这个问题?
SELECT adverts.*,
( SELECT advert_images.imagethumbpath FROM advert_images WHERE advert_images.advert_id = adverts.advert_id ORDER BY image_id ASC LIMIT 1 ) as imagethumbpath,
( SELECT count(advert_images.advert_id) from advert_images WHERE advert_images.advert_id = adverts.advert_id ) AS num_photos
FROM adverts
WHERE num_photos > 0
ORDER BY date_updated DESC
LIMIT 10
答案 0 :(得分:1)
您可以使用HAVING
代替WHERE
SELECT adverts.*,
( SELECT advert_images.imagethumbpath FROM advert_images WHERE advert_images.advert_id = adverts.advert_id ORDER BY image_id ASC LIMIT 1 ) as imagethumbpath,
( SELECT count(advert_images.advert_id) from advert_images WHERE advert_images.advert_id = adverts.advert_id ) AS num_photos
FROM adverts
HAVING num_photos > 0
ORDER BY date_updated DESC
LIMIT 10
答案 1 :(得分:0)
你必须使用having子句而不是where
having num_photos > 0
答案 2 :(得分:0)
如果您的大部分广告都有图片,那么这应该非常快。
select a.advert_id
,a.date_updated
,b.imagethumbpath
from adverts a
join advert_images b on(a.advert_id = b.advert_id)
where b.image_id =
(select min(c.image_id)
from advert_image c
where c.advert_id = b.advert_id)
order
by date_updated desc
limit 10;
您应该对adverts(date_updated)
和advert_images(advert_id, image_id)
进行索引。
让我知道这是如何解决的。