MySQL Inner Join表基于列值

时间:2011-03-28 02:14:14

标签: mysql sql

假设我有一个具有以下结构的表'stats':
tableName | id | pageViews
tableName列对应于数据库中的单独表。

针对“统计信息”运行查询时,针对tableName列结果进行内部联接以获取每个表的数据的最佳方法是什么?我正在考虑在foreach中运行动态选择,然后合并结果。 E.g:

foreach($tableNames as $tableName) {
    $sql = "SELECT      *
            FROM        stats s
            INNER JOIN  $tableName tbl ON s.id = tbl.id
            WHERE       tableName = '$tableName'";
}

2 个答案:

答案 0 :(得分:7)

要拥有所有表的统计信息,您可以使用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'
   )
;

答案 1 :(得分:3)

您是否可以先加入所有牌桌,然后再加工?

SELECT *
    FROM stats s
    LEFT OUTER JOIN tbl1 ON s.id = tbl.id
    LEFT OUTER JOIN tbl2 ON s.id = tbl2.id

然后你在之后的程序中获取所需的值?

您应该尽量减少对数据库进行的查询次数,尽可能尝试一次性。

否则,请考虑存储过程

这是一种简单的方法(带有管理费用),我相信其他人也会帮助你。

相关问题