简体   繁体   中英

how to select two columns from two tables in mysql

I am trying to execute this query but i got error " Undefined index: lname".I want to count row from one column(fname) from table a and select column(lname) from other table b. so please help me.

    $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>";
    }

If you still get an error you can try to fetch both separately:

$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>";
   }

You need to use an alias. Use this:

$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>";
}

Try this code:

$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>";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM