简体   繁体   中英

Retrieve data from table using data retrieved from another table

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>"; 
?>

Why not this:

$data = mysql_query("SELECT firstname, lastname FROM YYY WHERE id ". $row['client_id']) ;
or die(mysql_error()); 

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...

用这个

  SELECT firstname, lastname FROM YYY WHERE id IN (SELECT client_id FROM XXX WHERE id=8 )

Just to answer the question:

$sql = "SELECT firstname, lastname FROM YYY WHERE client_id = ".$row['client_id']."";

But, as mentioned, do not use mysql_ functions, ase they are deprecated and will be removed in the future. This means that your code won't be running for a long time if you still use them.

Also, I guess it would be more efficient and more elegant to solve this with MySQL JOIN s. If you have difficulty in implementing this, just ask for help.

A simple example for a query with a JOIN is the following:

$sql = "
SELECT 
  yy.firstname, yy.lastname 
FROM xx 
JOIN yy ON yy.client_id = xx.client_id 
WHERE xx.id = ".$yourID."
";

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