0

Here's what I have:

  1. 1 database table containing approx 2000 records, indexed. (The important column is a string of 25 characters).
  2. An array containing approx 30 strings of 25 characters.

What I'd like to do:

  1. I need to check the array against the database table to find any string matches.
  2. I need to be able to identify what values in the array only match any in the table, if any

I don't really want to have to run each string in the array against the table in a separate query fashion using a loop, I'm thinking there must be a more efficient way to do this.

Any ideas would be appreciated. I'm using PHP 5.4.3 and MySQL.

4

3 回答 3

3

只需使用 IN 子句:-

SELECT somecolumn
FROM someTable
WHERE someCoumn IN ('a string', 'another string', 'etc')

可能在 php 中执行此操作(假设数组已经转义为 SQL 安全):-

$sql = "SELECT somecolumn
FROM someTable
WHERE someCoumn IN ('".implode("','", $someArray)."')";

如果您想计算每个项目上有多少匹配项(包括具有 0 的匹配项),那么这样的事情可能会更好:-

<?php

$result = $db->query("CREATE TEMPORARY TABLE CheckValues
(CheckValue varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`CheckValue`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 ;");

$result = $db->query("INSERT INTO CheckValues (CheckValue) VALUES('".implode("','", $someArray)."')");

$result = $db->query("SELECT CheckValue, COUNT(b.someCoumn) AS someCount
FROM CheckValues a
LEFT OUTER JOIN someTable b ON a.CheckValue = b.someCoumn
GROUP BY CheckValue");

while ($row = $result->fetch_assoc()) 
{
    echo "$row[CheckValue] - $row[someCount] <br />";
}

?>
于 2013-03-05T09:18:46.317 回答
2

正如其他人所建议的,您可以使用IN从句。这是一个使用MySQLi代替的示例,mysql_*因此您不必担心逃逸和注入。

$criteria=array(/* string-to-search */);
$sql="SELECT * FROM `table` WHERE `column` IN (".implode(",",array_fill(0,count($criteria),"?")).")";
$stmt=$mysqli->prepare($sql);

call_user_func_array(array($stmt,"bind_param"),array_merge(array(str_repeat("s",count($criteria))),$criteria));

$stmt->execute();
$result=$stmt->get_result();
于 2013-03-05T09:28:50.477 回答
1

您应该使用 MYSQL WHERE IN 子句。

使用如下:

SELECT * FROM TABLE_NAME WHERE COLUMN_NAME IN ('.implode(', ', $array).')'
于 2013-03-05T09:19:37.177 回答