Right now I am using a loop to go trough 100 IDs that I have. Each iteration of the loop does a query to the DB. In my opinion this is not efficient at all. I want to put this into one query. But it's not going my own way to say the least.
Here is the query I have been playing around with. It should give a good idea of what I am trying to do.
SELECT
festival_backers.clown_id,
festival_backers.user_id
FROM festival_backers
INNER JOIN users ON users.id = festival_backers.user_id
LEFT JOIN festival_backers AS lesser ON lesser.festival_id = 1632 AND lesser.clown_id = festival_backers.clown_id
WHERE festival_backers.festival_id = 1632
AND lesser.clown_id IN (136541, 1000376982, 222329...)
AND lesser.user_id NOT IN (136541, 1000376982, 222329...)
GROUP BY festival_backers.clown_id
HAVING COUNT(lesser.clown_id) < 3
ORDER BY (festival_backers.amount + (festival_backers.free_vote / 10)) DESC
LIMIT 300;
I am getting nothing with this query.
The result I am looking for.
clown_id | user_id
-----------------------------
136541 | 21324
136541 | 57889
136541 | 89632
1000376982 | 56432
1000376982 | 57343
1000376982 | 23345
222329 | 45456
222329 | 77854
222329 | 67789
I am trying to get the users that have backed a clown. But only three of them not more than that. I was able to make query where I got more than three but that's not good (they are just too many).
The reason I use NOT IN
(following example) is because user_id
is also used for clowns because they are also users.
AND lesser.user_id NOT IN [...]
I tried following this: https://stackoverflow.com/a/30269273/736910
Is there a way to maybe use a function or something to limit the amount of results return with a join to three? Or is there some other way to get the result I am looking for?
UPDATE
I have different queries... Here is another example that also returns nothing:
SELECT
festival_backers.clown_id,
festival_backers.user_id
FROM festival_backers
INNER JOIN users ON users.id = festival_backers.user_id
INNER JOIN festival_backers AS lesser ON lesser.festival_id = 1632 AND lesser.clown_id = festival_backers.clown_id
WHERE festival_backers.festival_id = 1632
AND lesser.clown_id IN (136541, 1000376982, 222329...)
AND lesser.user_id NOT IN (136541, 1000376982, 222329...)
GROUP BY festival_backers.clown_id
HAVING COUNT(festival_backers.clown_id) < 3
ORDER BY (festival_backers.amount + (festival_backers.free_vote / 10)) DESC
LIMIT 300;