doulei8861 2013-08-12 11:45
浏览 32
已采纳

使用从另一个表中检索的数据从表中检索数据

I need to get the id from one table in a database and use that id as a "key" in order to get the name from another table. For example

 $result2 = mysql_query("SELECT * FROM XXX WHERE id=8 ") 
 or die(mysql_error());  

 while($row = mysql_fetch_array( $result2 )) {

echo $row['client_id'];

Here i get the client_id from the table 1. Now how do i implement that into this so that it returns the name and last name only of those that have the above id

$data = mysql_query("SELECT firstname, lastname FROM YYY WHERE ???? :S ") 
or die(mysql_error()); 
Print "<table border cellpadding=3>"; 
while($info = mysql_fetch_array( $data )) 
   { 
   Print "<tr>"; 
   Print "<th>fname:</th> <td>".$info['firstname'] . "</td> "; 
   Print "<th>lname:</th> <td>".$info['lastname'] . " </td></tr>"; 
} 
Print "</table>"; 
?>
  • 写回答

4条回答 默认 最新

  • donglvchu9143 2013-08-12 11:50
    关注

    If you only need to take the client_id from XXX table, use a subquery:

    $data = mysql_query("SELECT firstname, lastname FROM YYY WHERE id IN (SELECT client_id FROM XXX WHERE id=8 )") .
    

    If XXX.id is PRIMARY KEY, then that subquery will return just one row, so instead if using id IN (SEL...), use id = (SEL...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)