我想要獲取用戶在不同表中輸入的記錄數。 DB的模式是:根據加入從不同表中選擇記錄數
+-----------------------+
| Survey Master |
+----------------+------+
| Field | Key |
+----------------+------+
| id | PK |
| Username | |
| FamilyMasterId | FK |
+----------------+------+
+------------+------+
| Family Master |
+------------+------+
| Field | Key |
+------------+------+
| id | PK |
+------------+------+
+-----------------------+
| Family Detail |
+----------------+------+
| Field | Key |
+----------------+------+
| id | PK |
| FamilyMasterId | FK |
+----------------+------+
+-----------------------+
| Travel Master |
+----------------+------+
| Field | Key |
+----------------+------+
| id | PK |
| FamilyDetailId | FK |
+----------------+------+
+-----------------------+
| Travel Detail |
+----------------+------+
| Field | Key |
+----------------+------+
| id | PK |
| TravelMasterId | FK |
+----------------+------+
我希望看到每個用戶在每個表是這樣創造的記錄數:
-
:
- Find Records from Different Tables
- Select count(*) from multiple tables
- http://www.sqlines.com/mysql/how-to/join-different-tables-based-on-condition
- http://www.informit.com/articles/article.aspx?p=30875&seqNum=5
- SQL: Combine Select count(*) from multiple tables
Username SurveyMaster FamilyMaster FamilyDetail TravelMaster TravelDetail
---------- -------------- -------------- -------------- -------------- --------------
User001 59 47 36 26 12
User002 88 76 64 42 25
User003 49 44 35 25 15
User004 77 69 55 45 37
查看以下鏈接後
我能寫這個查詢,但它給出了相同的記錄中的所有列:
SELECT USERNAME, COUNT(USERNAME) SURVEYMASTER, COUNT(USERNAME) FAMILYMASTER, COUNT(USERNAME) FAMILYDETAIL, COUNT(USERNAME) TRAVELMASTER, COUNT(USERNAME) TRAVELDETAIL FROM
((SELECT CREATEUSER USERNAME FROM SURVEYMASTER
)
UNION ALL
(SELECT SM.CREATEUSER USERNAME FROM SURVEYMASTER SM
INNER JOIN FAMILYMASTER FM ON FM.ID = SM.FAMILYMASTERID
)
UNION ALL
(SELECT SM.CREATEUSER USERNAME FROM SURVEYMASTER SM
INNER JOIN FAMILYMASTER FM ON FM.ID = SM.FAMILYMASTERID
INNER JOIN FAMILYDETAIL FD ON FM.ID = FD.FAMILYMASTERID
)
UNION ALL
(SELECT SM.CREATEUSER USERNAME FROM SURVEYMASTER SM
INNER JOIN FAMILYMASTER FM ON FM.ID = SM.FAMILYMASTERID
INNER JOIN FAMILYDETAIL FD ON FM.ID = FD.FAMILYMASTERID
INNER JOIN TRAVELMASTER TM ON FD.ID = TM.FAMILYDETAILID
)
UNION ALL
(SELECT SM.CREATEUSER USERNAME FROM SURVEYMASTER SM
INNER JOIN FAMILYMASTER FM ON FM.ID = SM.FAMILYMASTERID
INNER JOIN FAMILYDETAIL FD ON FM.ID = FD.FAMILYMASTERID
INNER JOIN TRAVELMASTER TM ON FD.ID = TM.FAMILYDETAILID
INNER JOIN TRAVELDETAIL TD ON TM.ID = TD.TRAVELMASTERID
)
) T
GROUP BY USERNAME
ORDER BY USERNAME
編輯
這裏是關係描述:
- FamilyMasterId是SurveyMaster和FamilyDetail 表中的外鍵。
- FamilyDetailId是TravelMaster表中的外鍵。
- TravelMasterId是TravelDetail表中的外鍵。
如果性能是不是一個問題,你可以使用一個單獨的子查詢中獲取每個計數。順便說一句,表格之間的關係並不清楚。 – FLICKER
'以獲得用戶在不同表中輸入的記錄的數量** **每個表中都需要USERID **例如created_by_userid –
@Used_By_Already沒有辦法讓我們可以通過所有表格之間的連接來計數 –