简体   繁体   中英

Is there a more efficient way to compress these mysql queries?

Say if I want to get 100 different users from the same table, I would have to create 100 different queries like below. I am only showing three queries as an example but you get my meaning.

I am wondering if there is a more efficient way to get as many users as I want from the same table? Important thing is that I need to have each user with their unique handle. For eg. $matrix_user_id_2, $matrix_user_id_3, $matrix_user_id_4. How can I go on about doing that?

$find_sponsor_2 = $db->prepare("SELECT user_id, filled_positions FROM matrix_2 WHERE user_id = :user_id");
$find_sponsor_2->bindValue(':user_id', 2);
$find_sponsor_2->execute();
$result_sponsor_2 = $find_sponsor_2->fetchAll(PDO::FETCH_ASSOC);
if(count($result_sponsor_2) > 0) {
  foreach($result_sponsor_2 as $row) {
    $matrix_user_id_2         = $row['user_id'];
    $filled_positions_2         = $row['filled_positions'];
  }
} else {
  $errors[] = 'User Id 2 not found in Matrix.';
}

$find_sponsor_3 = $db->prepare("SELECT user_id, filled_positions FROM matrix_2 WHERE user_id = :user_id");
$find_sponsor_3->bindValue(':user_id', 3);
$find_sponsor_3->execute();
$result_sponsor_3 = $find_sponsor_3->fetchAll(PDO::FETCH_ASSOC);
if(count($result_sponsor_3) > 0) {
  foreach($result_sponsor_3 as $row) {
    $matrix_user_id_3         = $row['user_id'];
    $filled_positions_3         = $row['filled_positions'];
  }
} else {
  $errors[] = 'User Id 3 not found in Matrix.';
}

$find_sponsor_4 = $db->prepare("SELECT user_id, filled_positions FROM matrix_2 WHERE user_id = :user_id");
$find_sponsor_4->bindValue(':user_id', 4);
$find_sponsor_4->execute();
$result_sponsor_4 = $find_sponsor_4->fetchAll(PDO::FETCH_ASSOC);
if(count($result_sponsor_4) > 0) {
  foreach($result_sponsor_4 as $row) {
    $matrix_user_id_4         = $row['user_id'];
    $filled_positions_4         = $row['filled_positions'];
  }
} else {
  $errors[] = 'User Id 4 not found in Matrix.';
} 

You can get all the information using 1 query. Why don't you do it like this?

 SELECT user_id, filled_positions FROM matrix_2 WHERE user_id in (2,3,4) // your ids here

and then you can iterate over the result set to check which one exists and which one doesn't.

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