有条件地限制mySQL的结果量?

Here is my query:

SELECT * FROM Photos WHERE Event_ID IN ($eventidstring)

I know I can limit the total amount of results from this query using LIMIT 5

I need the Limit the amount of results Per value in $eventidstring.

So if $eventidstring = 23,41,23*

*And there are 10 results WHERE Event_ID = 23, I want to limit this amount to 5. The same for all the other values in $eventidstring.

You may have some joy doing something similar to Oracle's RANK by PARITION in MySQL.

Sadly this feature is not available in MySQL though you can work around it using this method

Dump that in an inline view and then select those rows with rank <= 5;

Hence:

SELECT t.* FROM (
SELECT ( 
        CASE Event_id 
        WHEN @curEventId 
        THEN @curRow := @curRow + 1 
        ELSE @curRow := 1 AND @curEventId := Event_Id END
      ) AS rank,
      p.*
FROM      Photos p INNER JOIN (SELECT @curRow := 0, @curEventId := '') r
ORDER BY p.Event_Id DESC
) t
WHERE t.rank <= 5 ORDER BY t.Event_Id asc;

Consider how you are going to 'choose' the top five by Event_Id too. You can always add in more after the ORDER BY p.Event_Id DESC to decide this.

If I understand correctly and you want to get five of each, you can use this:

(SELECT * FROM Photos WHERE Event_ID = 23 LIMIT 5)
UNION
(SELECT * FROM Photos WHERE Event_ID = 41 LIMIT 5)
UNION
(SELECT * FROM Photos WHERE Event_ID = ... LIMIT 5)
...

Maybe with a SELECT UNION but you need a new select for each value:

SELECT * FROM Photos WHERE Event_ID = 23 LIMIT 5
UNION SELECT * FROM Photos WHERE Event_ID = 41 LIMIT 5
UNION SELECT ...

I take it you're writing that query somewhere inside your PHP, so you need to split the $eventidstring into it's component values, form a SELECT for each and UNION all after the first one.

You sould do this with a loop of some sort, and concatenate the query strings in the loop...