PHP MySql比较不同表中的2列,执行计算&输出结果

时间:2016-08-14 09:04:57

标签: php mysql

我有两张表完全相同的结构,名为table_new& table_old分别。表格结构如下:

CREATE TABLE IF NOT EXISTS `table_new` (
  `Club_Number` int(11) default NULL,
  `Club_Name` varchar(60) character set utf8 default NULL,
  `Active_Members` int(11) default NULL,
  `Goals_Met` int(11) default NULL,
  `Last_Updated` date NOT NULL,
  `id` int(6) NOT NULL auto_increment,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

这就是我想要做的事情:

第1步。 将table_new与table_old进行比较,其中table_new.Active_Members大于table_old.Active_Members OR table_new.Goals_Met大于table_old.Goals_Met WHERE table_new.Club_Number等于table_old.Club_Number

第2步。 如果找到肯定的东西(结果大于零),计算之间的差异:

  1. table_new.Active_Members和table_old.Active_Members&回应结果
  2. table_new.Goals_Met和table_old.Goals_Met&回应结果
  3. 我如何使用PHP& amp; MySQL的?非常感谢你的帮助。

3 个答案:

答案 0 :(得分:0)

此查询将为您提供所需的输出

SELECT table_new.Active_Members, table_old.Active_Members, table_new.Goals_Met, table_old.Goals_Met FROM table_new 
INNER JOIN table_old ON table_new.id = table_old.id
WHERE (table_new.Active_Members > table_old.Active_Members OR table_new.Goals_Met > table_old.Goals_Met) 
AND table_new.Club_Number = table_old.Club_Number

答案 1 :(得分:0)

此查询对您有所帮助

select convert(t_n.Active_Members - t_o.Active_Members, SIGNED) as 'Active Members',
convert(t_n.Goals_Met - t_o.Goals_Met, SIGNED) as 'Goals Met'
from table_new as t_n inner join 
table_old as t_o 
on t_n.Club_Number = t_o.Club_Number
where t_n.Active_Members > t_o.Active_Members OR 
t_n.Goals_Met > t_o.Goals_Met;

答案 2 :(得分:0)

PHP脚本显示差异。

$result=$db->query('SELECT tabn.`Active_Members` as active_new, tabo.`Active_Members` as active_old, tabn.`Goals_Met` as goals_new, tabo.`Goals_Met` as goals_old FROM `table_new` as tabn LEFT JOIN `table_old` as tabo ON tabn.`Club_Number`=tabo.`Club_Number` WHERE (tabn.`Active_Members` > tabo.`Active_Members`) OR (tabn.`Goals_Met` > tabo.`Goals_Met`)');

if(count($result) > 0)
while($row = $result->fetch_assoc()){

echo 'Difference in Active_Members is: '.$row['active_new'] - $row['active_old']."\n";
echo 'Difference in Goals_Met is: '.$row['goals_new'] - $row['goals_old']."\n";

}