[英]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. 假设我想从同一张表中获得100个不同的用户,则必须创建100个不同的查询,如下所示。 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. $ 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. 您可以使用1个查询来获取所有信息。 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. 然后您可以遍历结果集以检查哪个存在,哪个不存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.