2010-01-17 20 views
7

Tengo una tabla en mi DB llamada "estudiantes" que contiene las siguientes columnas (student_id, student_name, year_of_birth) .y una matriz de años Estoy tratando de hacer una consulta que obtiene 10 student_id de cada año en (años) matriz.Límite múltiple mysql en una instrucción sql

podría escribir

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) 

Pero eso sería muy lento ¿Hay otras opciones Gracias

Respuesta

1

Si la preocupación es que las consultas volverán varios conjuntos de resultados, que podría lanzar un UNION ALL entre cada 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 
... 

Esta lata de Por supuesto, se combina con el enfoque de alexn de generar la consulta de una variedad de años.

hago no creo que esto le dará un rendimiento mucho mejor que las consultas separadas, pero podría (en una versión futura de MySQL), ya que da el motor de base de datos un poco más de información sobre lo que está haciendo.

0

Utilice una sub-consulta que une de nuevo a la mesa:

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) 

Sólo hay un problema sin embargo: esto sólo funcionará si usa MySQL 5.1 o superior.

La alternativa es usar una declaración de la Unión:

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

Esto funcionará para una gama más amplia de las versiones de MySQL.

0

Este es también uno de los ejemplos para encontrar el año bisiesto con múltiples límites

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

por qué no simplemente hacer eso:

$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']; 
} 

Su gama $students contendrá las matrices de las identificaciones de estudiante con las teclas como los años de nacimiento.

+0

si le preocupa más el límite, puede limitarlo en php, con un contador. –

Cuestiones relacionadas