在一个SQL语句中使用多个limit子句的MySQL。

11
我在我的数据库中有一个名为“students”的表,其中包含以下列(student_id,student_name,year_of_birth),以及一系列年份。 我试图编写一个查询,该查询获取(years)数组中每个年份的10个student_id。
我可以这样写:
SELECT student_id FROM `students` WHERE year_of_birth=1950 LIMIT 10;
SELECT student_id FROM `students` WHERE year_of_birth=1951 LIMIT 10;
SELECT student_id FROM `students` WHERE year_of_birth=1952 LIMIT 10;
SELECT student_id FROM `students` WHERE year_of_birth=1953 LIMIT 10;
(and so on)

但那会非常耗时,还有其他选项吗?谢谢

6个回答

7

2

如果你担心查询会返回多个结果集,你可以在每个 SELECT 之间添加一个 UNION ALL

SELECT student_id FROM `students` WHERE year_of_birth=1950 LIMIT 10
UNION ALL
SELECT student_id FROM `students` WHERE year_of_birth=1951 LIMIT 10
UNION ALL
...

当然,这可以与alexn的方法结合起来,从年份数组生成查询。

我认为这不会比单独查询带来更好的性能,但它可能会在MySQL的未来版本中实现,因为它提供了一些关于您正在执行的操作的额外信息。


1
使用链接回表的子查询:
SELECT student_id FROM `students` AS s1
WHERE student_id IN 
  (SELECT s2.student_id FROM `students` AS s2
     WHERE s1.year_of_birth = s2.year_of_birth
     LIMIT 10)

只有一个问题:这仅适用于使用MySQL 5.1或更高版本的用户。

替代方法是使用union语句:

for ($year = 1950; $year < 2000; $year++) {
  $stmts[] = "SELECT student_id FROM `students` 
                WHERE year_of_birth = $year LIMIT 10";
}
$sql = implode(' UNION ALL ', $stmts;

这将适用于更广泛的MySQL版本。


1

这也是使用多个限制条件来查找闰年的示例之一。

select year_n from the_years

select distinct month_n from the_months,the_years where year_n=$P{Year}

(select distinct day_n from the_days,the_months where $P{Month} IN('Jan','Mar','May','Jul','Aug','Oct','Dec') limit 31)
UNION ALL
(select distinct day_n from the_days,the_months where $P{Month} IN('Apr','Jun','Sep','Nov') limit 30)
UNION ALL
(select distinct day_n from the_days,the_years,the_months where $P{Month}='Feb' and mod($P{Year},4)!=0 or mod($P{Year},100)=0  or mod($P{Year},400)=0  limit 28)
UNION ALL
(select distinct day_n from the_days,the_years,the_months where $P{Month}='Feb' and mod($P{Year},4)=0 and mod($P{Year},100)!=0 or mod($P{Year},400)=0 limit 29) 

0
为什么不简单地这样做呢?
$studentIds = array(1950, 1951, 1952, 1953);

$sql = "
   SELECT
        student_id,
        year_of_birth
    FROM
        students
    WHERE
        student_id IN (" . implode(',', $studentIds) . ")
";

$result = mysql_query($sql);

$students = array();
while($row = mysql_fetch_assoc($result)) {
    $students[$row['year_of_birth']] = $row['student_id'];
}

你的$students数组将包含学生ID数组,键为出生年份。


如果你更关心限制,你可以在 PHP 中使用计数器来限制。 - alexg

0

你可以试试这个:

SELECT first.*
    from (
    SELECT student_id FROM students WHERE year_of_birth=1950 LIMIT 0,10
    ) AS first
    UNION 
    SELECT second.*
    from 
    (
    SELECT student_id FROM `students` WHERE year_of_birth=1951 LIMIT 10;
    )as second

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接