Mysql access main table inside right joined subquery
SELE开发者_JAVA技巧CT id,region FROM ads
RIGHT JOIN (SELECT * FROM ads a2 WHERE a2.region=ads.region LIMIT 4) AS regions
ON regions.id=ads.id
Says "unknown column ads.region". How to access main table column region?
I need to fetch 4 rows for each region
Use:
SELECT a.id,
a.region
FROM ads a
RIGHT JOIN (SELECT t.*,
CASE
WHEN @region = t.region THEN @rownum := @rownum + 1
ELSE @rownum := 1
END as rank,
@region := t.region
FROM ADS t
JOIN (SELECT @rownum := 0, @region := 1) r
ORDER BY t.region) b ON b.id = a.id
AND b.region = a.region
AND b.rank <= 4
精彩评论