假设我有一个表'stats'具有以下结构:
tableName | id | pageViews
tableName列对应于数据库中的单独表.
针对"统计信息"运行查询时,内部联接对tableName列结果的最佳方法是获取每个表的数据?
我想在foreach中运行动态选择然后合并结果.例如:
foreach($tableNames as $tableName) {
$sql = "SELECT *
FROM stats s
INNER JOIN $tableName tbl ON s.id = tbl.id
WHERE tableName = '$tableName'";
}
Run Code Online (Sandbox Code Playgroud)
要拥有所有表的统计信息,可以使用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'
)
;
Run Code Online (Sandbox Code Playgroud)
使用Winfred的想法与LEFT JOINs.它会产生不同的结果,例如,其他表中的每个字段都在其自己的列中输出(并且会出现许多NULL).
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'
)
;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11346 次 |
| 最近记录: |