MySQL比较两个表并显示差异

laik7k3q  于 2023-05-16  发布在  Mysql
关注(0)|答案(1)|浏览(140)

我目前有两个表(主表和修订表),我正在试图找到一种更简单的方法(而不是一个很长的php脚本)来显示最新的两个条目之间的差异。我基本上有一个表,我显示每两行的差异。
使用者
| ID|名字|姓|生物|国家|地位|
| --------------|--------------|--------------|--------------|--------------|--------------|
| 1|约翰|史密斯公司|在这里说几句。|美国|活动|
| 二|杰克|琼斯|布拉布拉|英国|待定|
用户_修订
| ID|用户ID|名字|姓|生物|国家|地位|
| --------------|--------------|--------------|--------------|--------------|--------------|--------------|
| 1| 1|乔恩|史密斯公司|在这里说几句。|加拿大|活动|
| 二|1|乔恩|史密斯公司|在这里说几句。。|美国|活动|
| 三|1|约翰|史密斯公司|在这里说几句。额外的|美国|活动|
| 四个|1|约翰|史密斯公司|在这里说几句。|美国|活动|
| 五|1|约翰|史密斯公司|在这里说几句。|英国|活动|
| 六|1|约翰|斯米特|在这里说几句。|美国|待定|
| 七|1|约翰|史密斯公司|在这里说几句。|美国|活动|
我每次都显示表的最后两个条目并突出显示差异,但我相信可以更快地完成。
例如,我比较了Users_revisions 7 <->6,并在下一行6 5(姓氏+国家+状态)上显示差异(姓氏+状态<->),等等,直到您到达第一个条目并比较Users_revisions 1和Users 1。
| 身份证|名字|姓|生物|国家|地位|
| --------------|--------------|--------------|--------------|--------------|--------------|
| <->七六|- -一种|史密斯·<->斯密特|- -一种|- -一种|活动<->待定|
| <->六五|- -一种|斯密特·<->史密斯|- -一种|美国<->英国|待定<->活动|
等等

6yt4nkrj

6yt4nkrj1#

这不是很优雅,但可以帮助你在这个问题!

<?php
// get the last two entries
$sql = ""; // define the query, remember to use prepared statements to improve security in your code!
$result = mysqli_query($conn, $sql); // perform the query
// need a while loop because we are handling multiple rows, instead you could use mysqli_fetch_all()
$rows = Array();
while ($row = mysqli_fetch_array($result)){
    $rows[] = $row;
}
// now loop trough every column
$compared_rows = $rows[0]["ID"]."<->".$rows[1]["ID"]; // just the IDs of the compared rows
$comparison = Array();
for($i=2; $i<=6; $i++){ // Skip the ID columns
    $value = ($rows[0][$i] == $rows[1][$i]) ? "-" : $rows[0][$i]."<->".$rows[1][$i]; // if the values are same just return - , else return ValueA<->ValueB
    $comparison[$compared_rows][$i] = $value; // Put this column inside the final nested array, which can be easily handled
}

print_r($comparison); // Output the final array
?>

相关问题