2012-09-24 30 views
1

我有2個表所示:如何在SQL表中的2個數據之間進行選擇?

Table 1 
------- 
ID 
score 

Table 2 
------- 
ID 
score_from 
score_to 

如何從表2中得到ID,如果我根據表2 score_from和score_to在表1有得分= '12' ?

Contents of Table1: 
---------------------- 
ID   |Score | 
---------------------- 
1   |12  | 
---------------------- 
2   |40  | 
---------------------- 

Contents of Table2: 
------------------------------ 
ID  |score_from|score_to| 
------------------------------ 
1  |0   |20  | 
------------------------------ 
2  |21  |40  | 
------------------------------ 

如果我有得分= '12' 從表1,我怎麼可以編寫一個查詢來獲取ID =‘表2中1’?

回答

2

試試這個,

SELECT a.`ID`, a.`Score`, b.`ID`, b.`score_from`, b.`score_to` 
FROM table1 a, table2 b 
WHERE (a.score BETWEEN b.score_from AND b.score_to) AND 
     (a.score = 12) 

SQLFiddle Demo

,或者如果你只想要ID

SELECT b.`ID` 
FROM table1 a, table2 b 
WHERE (a.score BETWEEN b.score_from AND b.score_to) AND 
     (a.score = 12) 

SQLFiddle Demo

0
select t2.id from table t1 ,table t2 
where t1.score between t2.score_from and t2.score_to; 
相關問題