I have this table that contains the ad id and the user id.
Any single user may have multiple ads.
I want to show only two ads per user (or one if he only has one). The output must be random.
CREATE TABLE IF NOT EXISTS `ads` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_user` int(12) NOT NULL,
`title` varchar(255) DEFAULT NULL,
`url` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
)
Table contains this:
1, 1, 'erfw', 'google.pt'
2, 2, 'yhtg', 'google.pt'
3, 2, 'gfddfg', 'google.pt'
4, 3, 'ehgfd', 'google.pt'
5, 2, '435yet', 'google.pt'
6, 1, 'ikkt', 'google.pt'
7, 1, 'wyrths', 'google.pt'
The output should be:
1, 1, 'erfw', 'google.pt'
2, 2, 'yhtg', 'google.pt'
3, 2, 'gfddfg', 'google.pt'
4, 3, 'ehgfd', 'google.pt'
6, 1, 'ikkt', 'google.pt'
The output must be different from time to time, to get all ads randomly.
In MySQL, doing any Greatest-n-per-group would make use of MySQL variables Preserve the last “thing”, and another for your “numbering” assignment (which you want as random in this case)
The “HAVING” clause is critical to understand in that this clarifies that the “HAVING” clause is applied AFTER any “GROUP BY” or “ORDER BY” and is applied to AFTER the record is considered in the result set (and not optimized with any WHERE clause).
That said, we query from ads, ordered by the user’s ID, but random second. This forces all the person’s “ads” as randomized. After that, the @ variables are applied and building up a sequence count per user. The having clause is then applied, and as soon as it gets to 3 or more, the results are thrown OUT of the final result set. And you are left with AT MOST 2 ads per user.
needs to be done first to ensurshould query the data ordered