2016-08-30 51 views
0

文件表(req1-7是需求的ID從另一個表)如何從另一個表中通過他們的ID從另一個表中獲取值?

| document_id | document_name | document_amount | req_1 | req_2 | req_3 | req_4 | req_5 | req_6 | req_7 | 
|  1  | Diploma  |  40   | 1 | 3 | 4 |  4 | 6 | 7 | 8 | 

要求表

| requirement_id | requirement_name | 
| 1   | 1 x 1 picture | 
| 2   | 2 x 2 picture | 
| 3   | Registration form| 
| 4   | Clearance  | 
| 5   | Medical cert  | 
| 6   | xray result  | 
| 7   | excuse letter | 
| 8   | affidavit  | 
| 9   | comsoc clearance | 

預期的結果是類似的文件表,但與相應的顯示的要求了名他們身份證的價值。

我想知道正確的語法來查詢這些

到目前爲止,我的查詢是:

SELECT * FROM document_tbl 
      WHERE requirement1,requirement2,requirement3,requirement4,requirement5,requirement6,requirement7 
      IN (
       SELECT requirement_name FROM requirements_tbl WHERE requirement_id=requirement1,requirement2,requirement3,requirement4,requirement5,requirement6,requirement7)"; 

但我screwedup莫名其妙。先謝謝您的幫助。我會很感激。

+1

它與PHP有什麼關係? – Aaron

+0

你用這個查詢得到了什麼輸出? – phil652

+1

這是編寫需求的低效方法。我建議你規範化你的數據庫。參考這個:http://www.studytonight.com/dbms/database-normalization –

回答

0

像這樣:

SELECT d.document_id, 
    d.document_name, 
    d.document_amount, 
    r1.requirement_name AS req_1, 
    r2.requirement_name AS req_2, 
    r3.requirement_name AS req_3, 
    r4.requirement_name AS req_4, 
    r5.requirement_name AS req_5, 
    r6.requirement_name AS req_6, 
    r7.requirement_name AS req_7 
FROM documents AS d, 
    requirements AS r1, 
    requirements AS r2, 
    requirements AS r3, 
    requirements AS r4, 
    requirements AS r5, 
    requirements AS r6, 
    requirements AS r7 
WHERE d.req_1 = r1.requirement_id 
    AND d.req_2 = r2.requirement_id 
    AND d.req_3 = r3.requirement_id 
    AND d.req_4 = r4.requirement_id 
    AND d.req_5 = r5.requirement_id 
    AND d.req_6 = r6.requirement_id 
    AND d.req_7 = r7.requirement_id 

等。

+0

這適用於@MartynasTumas。但正如他們上面所述。它以緩慢的方式處理輸出,但它提供了準確的結果。謝謝 –

1

中間體表(document_requirements)

| document_id | requirement_id | 
|  1  | 1    | 
|  1  | 3    | 
|  1  | 4    | 
|  1  | 6    | 
|  1  | 6    | 
|  1  | 7    | 
|  1  | 8    | 

查詢

SELECT d.document_id,dr.requirement_id,r.requirement_name 
FROM documents AS d 
JOIN document_requirements AS dr ON (dr.document_id=d.document_id) 
JOIN requirements AS r ON (r.requirement_id=dr.requirement_id) 
WHERE d.document_id = 1; 
+0

無法水平顯示要求嗎? @穆罕默德亞辛?不能用相應的名字顯示嗎? –

+0

這可能與7個子選擇,但如上面提到的其他人一樣,這將是非常低效的。使用這種方法,您仍然可以循環查看結果,並獲取上面查詢中包含的名稱,作爲「r.requirement_name」 –

+0

@Mohammed Yasin我是否必須創建另一個名爲document_requirements的表:如果是這樣,那麼名稱是它包含的列?對不起,不回覆。我忙於學校項目。 –

相關問題