如果匹配则匹配两个表中的数据。显示名称和消息

时间:2012-11-27 08:29:18

标签: php mysql

我在mysql中有两个表格。以下是我的剧本。

<?php
$conn=mysql_connect("localhost",'root','');
mysql_select_db('test');

$sql    = "SELECT data_student.name,ozekimessagein.msg 
            FROM ozekimessagein,data_student
            WHERE ozekimessagein.sender=data_student.sender 
            ORDER BY ozekimessagein.msg";

$res=mysql_query($sql);
$cn=mysql_num_rows($res);
for($x=0;$x<$cn;$x++)
{
    list($name,$msg)=mysql_fetch_row($res);
    echo "<li>$name,$msg";
}
mysql_close($conn);
?>

只要data_student表中的发件人与ozekimessagein表中的发件人匹配,就应显示表data_student表中的名称和来自ozekimessagein的邮件。但它不起作用。

2 个答案:

答案 0 :(得分:0)

试试这个::

SELECT 

data_student.name,
ozekimessagein.msg 

FROM ozekimessagein 
inner join data_student     on ozekimessagein.sender=data_student.sender 

ORDER BY ozekimessagein.msg

答案 1 :(得分:0)

试试这个

 <?php
  $conn=mysql_connect('localhost','root','');
    mysql_select_db('test');

 $sql    = "

   SELECT s.name AS names, o.msg AS msgs
  FROM ozekimessagein o
  INNER JOIN data_student s
   ON o.sender = s.sender
   ORDER BY s.name";

  $res=mysql_query($sql);

  while ($row = mysql_fetch_assoc($res)) {

 echo "<li>".$row['names']." : ".$row['msgs']."</li>";
     }
  mysql_close($conn);
  ?>