This is the table i got with table name photos:
photo_id user_id
401 1
403 1
405 1
407 2
408 1
409 2
410 1
411 3
412 2
413 2
420 2
423 2
I am Currently Using the Query
SELECT *
FROM photos
WHERE user_id
IN ( 1, 2 )
LIMIT 0 , 6
Ids inside IN
can have multiple values not just two
What I Get Is
photo_id user_id
401 1
403 1
405 1
407 2
408 1
409 2
Without Having Proportionate values for each user_id
What I Want is Get Values in Equal Proportion from both UserIds. That is if fetching limit is 6 then i need 3 values or less than 3 if less than 3 elements exists from 1 and 3 values or less than 3 if less than 3 elements exists from 2
And If there are 3 user ids and fetching limit is 6; All three ids will have result with value of 2
photo_id user_id
401 1
403 1
405 1
407 2
409 2
412 2
I can Do it in Multiple queries ; But Is there any way to do it in single query;
Consider the following...
DROP TABLE IF EXISTS photos;
CREATE TABLE photos
(photo_id INT NOT NULL PRIMARY KEY
,user_id INT NOT NULL
);
INSERT INTO photos VALUES
(401 ,1),
(403 ,1),
(405 ,1),
(407 ,2),
(408 ,1),
(409 ,2),
(410 ,1),
(411 ,3),
(412 ,2),
(413 ,2),
(420 ,2),
(423 ,2);
SELECT x.*
, COUNT(*) rank
FROM photos x
JOIN photos y
ON y.user_id = x.user_id
AND y.photo_id <= x.photo_id
GROUP
BY x.photo_id
, x.user_id
ORDER
BY user_id
, rank;
+----------+---------+------+
| photo_id | user_id | rank |
+----------+---------+------+
| 401 | 1 | 1 |
| 403 | 1 | 2 |
| 405 | 1 | 3 |
| 408 | 1 | 4 |
| 410 | 1 | 5 |
| 407 | 2 | 1 |
| 409 | 2 | 2 |
| 412 | 2 | 3 |
| 413 | 2 | 4 |
| 420 | 2 | 5 |
| 423 | 2 | 6 |
| 411 | 3 | 1 |
+----------+---------+------+
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.