如何从mysql中的两个表中选择两列

时间:2012-10-18 13:40:15

标签: php mysql

  

我正在尝试执行此查询,但我收到错误“Undefined index:   lname“。我想从表a和中计算一列(fname)中的行   从其他表b中选择列(lname)。所以请帮助我。

    $result = mysql_query("SELECT COUNT(fname),lname FROM a,b");
    while ($row = mysql_fetch_array($result))
    {
      echo "<tr><td>";
      echo $row['lname'];
      echo "</td>";
      echo "<td>";
      echo $row['COUNT(fname)'];
      echo "</td></tr>";
    }

3 个答案:

答案 0 :(得分:3)

如果仍然出现错误,可以尝试单独获取两者:

$result = mysql_query("SELECT COUNT(fname) FROM a");
while ($row = mysql_fetch_array($result))
  {
    echo "<tr><td>";
    echo $row['COUNT(fname)'];
    echo "</td></tr>";

  }

$result1 = mysql_query("SELECT lname FROM b");
while ($row = mysql_fetch_array($result1))
    {
      echo "<tr><td>";
      echo $row['lname'];
      echo "</td></tr>";
   }

答案 1 :(得分:2)

您需要使用别名。使用此:

$result = mysql_query("SELECT COUNT(fname) AS countfname,lname FROM a,b");
while ($row = mysql_fetch_array($result))
{
  echo "<tr><td>";
  echo $row['lname'];
  echo "</td>";
  echo "<td>";
  echo $row['countfname'];
  echo "</td></tr>";
}

答案 2 :(得分:1)

试试这段代码:

$result = mysql_query("SELECT COUNT(a.fname) as fname,b.lname as lname FROM a,b");
while ($row = mysql_fetch_array($result))
{
  echo "<tr><td>";
  echo $row['lname'];
  echo "</td>";
  echo "<td>";
  echo $row['COUNT(fname)'];
  echo "</td></tr>";
}