要讓所有表的統計數據,你可以使用UNION,有2個或更多的選擇,一個爲每個表:
(SELECT s.*
, table1.title AS name --or whatever field you want to show
FROM stats s
JOIN $tableName1 table1
ON s.id = table1.id
WHERE tableName = '$tableName1'
)
UNION ALL
(SELECT s.*
, table2.name AS name --or whatever field you want to show
FROM stats s
JOIN $tableName2 table2
ON s.id = table2.id
WHERE tableName = '$tableName2'
)
UNION ALL
(SELECT s.*
, table3.lastname AS name --or whatever field you want to show
FROM stats s
JOIN $tableName3 table3
ON s.id = table3.id
WHERE tableName = '$tableName3'
)
;
使用溫弗雷德的想法與LEFT JOIN
秒。它產生不同的結果,例如其他表中的每個字段都會輸出到它自己的列中(並且會出現很多空值)。
SELECT s.*
, table1.title --or whatever fields you want to show
, table2.name
, table3.lastname --etc
FROM stats s
LEFT JOIN $tableName1 table1
ON s.id = table1.id
AND s.tableName = '$tableName1'
LEFT JOIN $tableName2 table2
ON s.id = table2.id
AND s.tableName = '$tableName2'
LEFT JOIN $tableName3 table3
ON s.id = table3.id
AND s.tableName = '$tableName3'
--this is to ensure that omited tables statistics don't appear
WHERE s.tablename IN
('$tableName1'
, '$tableName2'
, '$tableName3'
)
;
你說:* tableName列對應於數據庫中的單獨表* *。 「id」對應什麼?我是否正確理解此統計表中有關於每個表的每一行的統計信息?因此,統計信息中的每一行都將「pageViews」存儲在表「tableName」中的「id」中? – 2011-03-28 06:13:48