比较不同表中的行

时间:2013-12-08 10:05:02

标签: php mysql

我在Mysql中有两个不同的表,我希望php比较表:电子邮件和帐户名称行,然后用电子邮件显示名称。
这就是我得到的:

<?php
require('./config.php');
mysql_connect($host, $user, $pass) or
die("Could not connect: " . mysql_error());
mysql_select_db($db);

$result = mysql_query("SELECT name FROM accounts");
 $result2 = mysql_query("SELECT email, name FROM emails");
$row = mysql_fetch_array($result, MYSQL_NUM);
$row2 = mysql_fetch_array($result2, MYSQL_NUM);
{
    echo ('<bold>Name  Email</bold><br>');
    echo ('<bold>'. $row[0] .  $row2[0] . '</bold><BR>');
    }


mysql_free_result($result);
?>

1 个答案:

答案 0 :(得分:0)

使用LEFT JOIN。试试这个:

<?php
require('./config.php');
mysql_connect($host, $user, $pass) or
die("Could not connect: " . mysql_error());
mysql_select_db($db);

$query = mysql_query("SELECT e.name,e.email FROM accounts a
                     LEFT JOIN emails e ON a.name = e.name");
while($row = mysql_fetch_array($query, MYSQL_NUM))
{
echo "<table><tr><td>";
echo "<bold>Name  Email</bold></td></tr>";
echo "<tr><td><bold>$row[0] $row[1]</bold></td></tr>";
echo "</table>";
}
mysql_free_result($result);
?>