2017-03-27 56 views
0

大家好,大家都對SQL查詢有點不滿。我有四個表SQL獲取與用戶相關的案例以及與該案例相關的文件數

users 
    +----+------------+-----------+--------+ 
    | id | first_name | last_name | active | 
    +----+------------+-----------+--------+ 
    | 1 | Joe  | Bloggs |  1 | 
    | 2 | John  | Doe  |  1 | 
    | 3 | Dave  | Smith  |  1 | 
    +----+------------+-----------+--------+ 

    cases 
     +----+-----------+-------------+ 
     | id | case_code | case_name | 
     +----+-----------+-------------+ 
     | 1 | THEC12C | Test Case 1 | 
     | 2 | ABCD23A | Test Case 2 | 
     +----+-----------+-------------+ 

case_creditors 
     +----+---------+-------------+ 
     | id | case_id | creditor_id | 
     +----+---------+-------------+ 
     | 1 |  1 |   3 | 
     | 2 |  2 |   1 | 
     +----+---------+-------------+ 

    case_files 
    +----+---------+----------+-----------+ 
    | id | case_id | filename | file type | 
    +----+---------+----------+-----------+ 
    | 1 |  1 | test.pdf | pfd  | 
    | 2 |  2 | file.txt | txt  | 
    | 3 |  2 | word.doc | doc  | 
    +----+---------+----------+-----------+ 

當我一個用戶登錄需要顯示的表與用戶accociated情況下連接到該案件的文件數,所以如果喬博客在頭loged見下表

+-----------+-------------+-------+ 
| Case Code | Case Name | Files | 
+-----------+-------------+-------+ 
| ABCD23A | Test Case 2 |  2 | 
+-----------+-------------+-------+ 

我一直在試圖編寫sql語句來做到這一點,但我陷入了查詢和流浪如果有人可以幫助給我一些指針。在SQL IVE GOR到目前爲止

SELECT * FROM cases 
(SELECT COUNT(*) FROM case_files WHERE case_files.case_id = cases.id) as Files 
JOIN case_creditors ON cases.id = case_creditors.case_id 
WHERE case_creditors.creditor_id = 1 
+0

它看起來像有可能會丟失一個表或者兩者的關係進行排序這一點。那麼,無論如何,或者,如果你想返回一個2的文件數,你的WHERE子句是沒有意義的。它應該是WHERE case_files.case_id = 2。或者,缺少的引用是case_files中的user_id。 – dat789

+0

嗨dal789 id不想讓文件與用戶關聯,但只有一個案例。 Evert案件可以有許多用戶和許多文件,所以我不認爲我需要文件和用戶之間的關係 –

回答

0

管理與

SELECT 
    ips_case.*, 
    COUNT(case_files.file_id) AS Files 
FROM 
    ips_case 
    LEFT JOIN case_files ON ips_case.id = case_files.case_id 
    JOIN case_creditors ON ips_case.id = case_creditors.case_id 
WHERE 
    case_creditors.creditors_id = 4 
GROUP BY 
    ips_case.id