简体   繁体   中英

The best way to select rows from several tables?

I am creating a php app and am now creating the DB interface code. In my APP their are three tables, user, network, user_network. They have the following columsn:

  user<-------------------->user_network<-------------------->network
user_ID                       un_ID                            network_ID
user_Name                     un_Member                        network_Name
                              un_Network                       network_Description

I have created the following query which querys the user_network table and returns the ID's of all networks which the user is a member of:

$STH = $DBH->query("SELECT * FROM user_network WHERE nm_Member ='$userID'");

I then pull the network_ID's from this array using the following code:

$DB_NetworkID = array();
foreach($STH as $row)
{
    $DB_NetworkID[$counter] = $row['nm_networkID'];
    $counter++;
}
print_r($DB_NetworkID);

The array now holds of all the network IDs that the user is a member of, like so

Array ( [0] => 1 [1] => 3 [2] => 5 [3] => 7 )   //network IDs = 1, 3, 5, 7

I would now like to pull rows from the networks tables, how do i go about about SELECTing rows from the networks database WHERE the ID is contained in the array?

Thanks for any help.

You should use a JOIN instead and make it a single query:

SELECT 
    *
FROM 
    user
INNER JOIN
    user_network
ON
    user.user_ID = user_network.un_ID
INNER JOIN
    network
ON 
    user_network.un_Network = network.network_ID
WHERE
    user_ID = '$userID'

That query will give you all networks that a user is member of.

If your problem is the comparison against an array, then an easy workaround is using FIND_IN_SET() like this:

$list = implode(",", $DB_NetworkID);   // turns it into "1,3,5,7"

... "SELECT * FROM foo WHERE   FIND_IN_SET(network_ID, '$list')";

For better performance you should construct an .. IN (?,?,..) clause however.

Of course using JOIN as "halfdan" said, is the best way. But I gonna answer your question:

If your array is like this:

$un = Array ( [0] => 1 [1] => 3 [2] => 5 [3] => 7 ) //network IDs = 1, 3, 5, 7

You can use a Foreach like this:

Foreach($un as $key => $value) {

and your query will be like this:

SELECT * FROM network WHERE network_ID ='$value'

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