PHP和多个DB选择

时间:2010-01-16 10:15:37

标签: php mysql database select

我有两个表需要提取信息,但第二个表中的数据取决于我从第一个表中获取的信息。有没有一种简单的方法来处理这个问题?

<?php
  mysql_connect('localhost', 'root', 'root') or die(mysql_error());
  mysql_select_db('stadium') or die(mysql_error());

  $result = mysql_query("SELECT * FROM events");

  $result2 = mysql_query("SELECT name FROM competitions WHERE id='$row[competition_id]' ");

  while($row = mysql_fetch_array($result)) {
    echo "<tr id=\"" . $row['id'] . "\"> \n<td>" . $row['name'] . "</td>";
    echo "<td>" . $row['competition_id'] . "</td>";
    echo "<td>" . $row['date'] . "</td></tr>";
  }
?>

1 个答案:

答案 0 :(得分:3)

使用JOIN

SELECT e.*, c.name as competition_name FROM events e LEFT JOIN competitions c on c.id = e.competition_id