假设我有一个具有以下结构的表“stats”:
表名 |编号 |页面浏览量
tableName 列对应于数据库中的单独表。
当针对“stats”运行查询时,针对 tableName
列结果进行内部联接以获取每个表的数据的最佳方式是什么?
我正在考虑在 foreach 中运行动态选择,然后合并结果。例如:
foreach($tableNames as $tableName) {
$sql = "SELECT *
FROM stats s
INNER JOIN $tableName tbl ON s.id = tbl.id
WHERE tableName = '$tableName'";
}
最佳答案
要获得所有表的统计信息,您可以使用 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'
)
;
将 Winfred 的想法与 LEFT JOIN
结合使用。它产生不同的结果,例如其他表中的每个字段都输出到它自己的列中(并且会出现许多 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'
)
;
关于基于列值的 MySQL Inner Join 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5454001/