一个sql语句中的mysql多重限制

时间:2010-01-17 14:36:31

标签: php mysql

我的数据库中有一个名为“students”的表包含以下列  (student_id,student_name,year_of_birth)。和年数组 我试图在(年)数组中创建一个每年获得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 个答案:

答案 0 :(得分:7)

“为MySQL中的一个组选择N行”:http://explainextended.com/2009/03/06/advanced-row-sampling/

答案 1 :(得分:2)

如果您担心查询会返回多个结果集,您可以在每个UNION ALL之间抛出SELECT

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的未来版本中)因为它为数据库引擎提供了更多关于你是什么的信息做。

答案 2 :(得分: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版本。

答案 3 :(得分:0)

这也是找到具有多个限制的闰年的示例之一

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) 

答案 4 :(得分: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数组,其中的键为出生年份。

答案 5 :(得分: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