SQL JOIN ON表名等于字段值

时间:2012-03-13 00:13:59

标签: php mysql sql join

我正在寻找一个mysql查询(使用php)一次一个地查看每个表,并且只显示与t_lastmod表中的键日期不匹配的所有结果。我不知道怎么说ON tablename = field value。

t_one

guid | name | lastmod
 1   |  Joe | 2012-01-01 01:00:00
 2   |  Tom | 2012-01-02 01:00:00
 3   |  Sue | 2012-03-01 02:00:00

t_two

guid | pet  | lastmod
 4   | cat  | 2012-01-01 01:00:00
 5   | dog  | 2012-01-02 01:00:00
 6   | fish | 2012-03-01 02:00:00

t_three

guid | fruit   | lastmod
 7   |  orange | 2012-01-01 01:00:00
 8   |  pear   | 2012-01-02 01:00:00
 9   |  grape  | 2012-03-01 02:00:00

t_lastmod

table_name | lastmod
   t_one   |  2012-01-01 01:00:00
   t_two   |  2012-01-02 01:00:00
   t_three |  2012-01-01 02:00:00

查询结果为:

t_one => 2 | Tom   | 2012-01-02 01:00:00
t_one => 3 | Sue   | 2012-03-01 02:00:00
t_two => 4 | cat   | 2012-01-01 01:00:00
t_two => 6 | fish  | 2012-03-01 02:00:00
t_three => 8 | pear | 2012-01-02 01:00:00
t_three => 9 | grape | 2012-03-01 02:00:00

到目前为止我的代码(在JOIN t_lastmod ON上需要帮助......)

$tables = array('t_one', 't_two', 't_three');

  foreach ($tables AS $table) {

    $query = " select $table.* from $table JOIN t_lastmod ON $table = t_lastmod.TABLE_NAME WHERE $table.lastmod != t_lastmod.lastmod ";

  }

1 个答案:

答案 0 :(得分:1)

select $table.* 
from $table 
JOIN t_lastmod ON '$table' = t_lastmod.TABLE_NAME 
WHERE $table.lastmod != t_lastmod.lastmod "