SQL查询来自不同范围区域的选定行

时间:2014-10-28 22:21:39

标签: mysql sql

我有一个带有实体的表entities,它具有唯一索引entity_id

例如,1< entity_id< 1000,但count(entity_id)< 500

我想创建一个选择的SQL查询:

  • 3个或更少的随机实体if entity_id< 200,
  • 3个或更少的随机实体,如果200< = entity_id< 400,
  • 3个或更少的随机实体,如果400< = entity_id< 600,
  • 3个或更少的随机实体,如果600< = entity_id< 800
  • 如果800< = entity_id
  • ,则为3个或更少的随机实体

所以,我想要一个查询并从实体范围的每个区域获取实体。如果一个或多个区域将是空的,那就没关系

我不知道如何实现它。

请协助

2 个答案:

答案 0 :(得分:0)

您可以编写一个返回表的函数,并在该函数中首先定义一个包含所需列的表,如:

DECLARE @ReturnTable TABLE (entity_id INT, column2 INT, etc.)

然后,声明另一个与实体相同但具有随机数列的表。

DECLARE @EntitiesCopy TABLE (entity_id INT, rand INT);

填充@EntitiesCopy表,如:

INSERT INTO @EntitiesCopy SELECT *, RAND() FROM entities

然后,编写插入语句,如:

INSERT INTO @ReturnTable(column1, column2) 
     SELECT TOP 3 * FROM @EntitiesCopy 
       WHERE (entity_id > 1) AND (entity_id < 200) 
       ORDER BY rand

同样,对于其他条件。

然后,

RETURN @ReturnTable

答案 1 :(得分:0)

我会使用UNION

select * from entities where entity_id between 2 and 199 order by rand() limit 3
UNION
select * from entities where entity_id between 200 and 399 order by rand() limit 3
UNION
select * from entities where entity_id between 400 and 599 order by rand() limit 3
UNION
select * from entities where entity_id between 500 and 799 order by rand() limit 3
UNION
select * from entities where entity_id between 700 and 999 order by rand() limit 3;

假设,当你说1&lt; entity_id&lt; 1000实体_id在2到999之间运行。