简体   繁体   English

MySQL从数组匹配中选择多个值

[英]mysql select multiple values from array match

I have an array lets say: Array ( [0] => 9 [1] => 7 [2] => 8 ) 我有一个数组可以说:Array([0] => 9 [1] => 7 [2] => 8)

I want to SELECT from a table (users) all phone numbers where userID matches one from the array (if there is a phone number listed). 我想从一个表(用户)中选择所有userID与数组中的一个匹配的电话号码(如果列出了电话号码)。

I want to do this without selecting all of the users from the database and only those that match that of the array and with actual phone numbers, should I do this in a loop? 我想执行此操作而不从数据库中选择所有用户,而仅选择那些与阵列的用户和实际电话号码匹配的用户,是否应该循环执行此操作?

Typically when I am doing an UPDATE, I do them within a foreach loop. 通常,当我执行UPDATE时,我会在foreach循环中执行它们。 Like so: 像这样:

foreach($userArr as $user) {
            $pid = $user;
            if(!$statement->execute()) {
                    throw new Exception($statement->error, $statement->errno);
            }
    }
$statement->close();

Can we do SELECT like that as well? 我们也可以这样做吗?

Thanks in advance for any advice. 在此先感谢您的任何建议。

If you want to select all these users, just do the follow: 如果要选择所有这些用户,请执行以下操作:

$idList = implode(',', $yourArray);
$sql = "SELECT * FROM users WHERE id IN($idList)";
// execute this $sql query

Try this: 尝试这个:

    <?php

    $array = array(9, 7, 8);

    $query = "SELECT * FROM mytable WHERE id = ";

    $condition = implode(' OR id = ', $array);

    $query .= $condition;

    echo $query;
?>

Output: 输出:

SELECT * FROM mytable WHERE id = 9 OR id = 7 OR id = 8

You should do the following: 您应该执行以下操作:

  1. Build a string to express the userid seperated by comma. 构建一个字符串以表示用逗号分隔的用户标识。 - Loop will be needed. -将需要循环。 ie id1, id2, id3 id1,id2,id3
  2. Build the query string to search for them. 构建查询字符串以搜索它们。

Example: 例:

SELECT * FROM `Users` WHERE id IN (id1, id2, id3)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM