简体   繁体   English

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

[英]Limit the amount of results from mySQL conditionally?

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 我知道我可以使用LIMIT 5限制此查询的结果总数

I need the Limit the amount of results Per value in $eventidstring. 我需要限制$ eventidstring中每个值的结果数量。

So if $eventidstring = 23,41,23* 因此,如果$ 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. * 并且有10个结果WHERE Event_ID = 23,我想将此数量限制为5。对于$ eventidstring中的所有其他值,该值相同。

You may have some joy doing something similar to Oracle's RANK by PARITION in MySQL. 您可能会高兴地做一些类似于MySQL中PARITION的Oracle RANK的事情。

Sadly this feature is not available in MySQL though you can work around it using this method 遗憾的是,尽管您可以使用此方法解决此功能,但该功能在MySQL中不可用

Dump that in an inline view and then select those rows with rank <= 5; 将其转储到嵌入式视图中,然后选择那些排名<= 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. 考虑一下如何通过Event_Id“选择”前五名。 You can always add in more after the ORDER BY p.Event_Id DESC to decide this. 您始终可以在ORDER BY p.Event_Id DESC之后添加更多内容来决定这一点。

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. 我认为您是在PHP内的某个地方编写该查询的,所以您需要将$eventidstring为它的组件值,在第一个之后对每个和UNION都形成一个SELECT。

You sould do this with a loop of some sort, and concatenate the query strings in the loop... 您可以通过某种循环来做到这一点,并在循环中连接查询字符串...

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 UNION,但是您需要为每个值进行新的选择:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM