2012-10-09 66 views
0

我是一個完整的SQL初學者。我正在使用查詢數據庫的程序,然後處理結果。默認查詢是:SQL:查詢整個數據庫

SELECT * 
FROM data, 
    questions, 
    users 
where users.U_Id = data.Subj_Id 
    and data.Subj_Id between 1 and 10 
    and data.Q_Id = questions.Q_Id 
    and questions.Q_Id between 1 and 10 
order by Subj_Id; 

我想它來查詢每個Subj_IdQ_Id。我不知道有多少,不同的科目有不同數量的問題。我應該如何改變上述查詢?

+0

請提供樣本數據和所需的輸出。 – RedFilter

回答

4

您可以像這樣重寫上述查詢。

select * 
from 
    data 
     inner join 
    users on users.U_Id = data.Subj_Id 
     inner join 
    questions on data.Q_Id = questions.Q_Id 
where data.Subj_Id between 1 and 10 
and questions.Q_Id between 1 and 10 
order by Subj_Id; 

這使得通過從數據上的過濾器中分離表格之間的連接更加清楚。 所以要查詢整個數據庫,你只要從上面取下where條款等

select * 
from 
    data 
     inner join 
    users on users.U_Id = data.Subj_Id 
     inner join 
    questions on data.Q_Id = questions.Q_Id 
order by Subj_Id; 
+0

知道了!謝謝。 「內連接」是什麼意思? –

+3

http://en.wikipedia.org/wiki/Join_(SQL) – podiluska