2010-01-17 63 views
7

我在我的數據庫中有一個名爲「students」的表格,其中包含以下列 (student_id,student_name,year_of_birth)和年數 我試着做一個查詢,獲得10個student_id年(年)數組。mysql在一個sql語句中的多重限制

我可以寫

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) 

但是,這將是非常耗時 是否有 謝謝

回答

1

如果您關注的是,查詢將返回多個結果集的任何其他選項,你可以扔

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 
... 

這可以的:在每個SELECT之間的UNION ALL當然可以結合alexn生成一系列年份查詢的方法。

我做認爲這會給你比單獨的查詢更好的性能,但它可能(在MySQL的未來版本),因爲它給人的數據庫引擎對你正在做的事情多一點信息。

0

使用子查詢鏈接回表:

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或更高版本。

另一種方法是使用一個聯合聲明:

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版本的工作。

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) 
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陣列作爲出生的年份。

+0

如果你更關心的限制,你可以限制它在PHP中,與計數器。 – 2013-11-28 16:32:36