SELECT DISTINCT多字段搜索?

时间:2010-04-03 00:09:47

标签: php mysql

我正在尝试搜索多个字段(zc_city,zc_zip和zc_state),与用户输入的单个值进行匹配。这三列应包含在结果中。这就是我现在所拥有的:

$q = strtolower($_GET["q"]);
if (!$q) return;

$sql = "SELECT DISTINCT zc_city AS zcity FROM search_zipcodes WHERE zc_city LIKE '$q%'";

$rsd = mysql_query($sql);
while($rs = mysql_fetch_array($rsd)) {
    $zcity = $rs['zcity'];
    echo "$zcity\n";
}

该表具有以下结构:

CREATE TABLE search_zipcodes (
  zc_zip VARCHAR(5),
  zc_lat FLOAT,
  zc_lon FLOAT,
  zc_city VARCHAR(80),
  zc_state CHAR(2) 
);

2 个答案:

答案 0 :(得分:0)

听起来好像你只想要一个OR:

$sql = "SELECT zc_city, zc_state, zc_zip FROM search_zipcodes WHERE zc_city LIKE '$q%' OR zc_state LIKE '$q%' OR zc_zip LIKE '$q%' ";

我仍然不确定你已经说明了这张桌子上的主键。如果是Zip或Zip + City,那么您不需要使用DISTINCT。如果您可以为同一个城市,州和邮政编制多个条目,那么您可以使用GROUP BY,如下所示:

$sql = "SELECT zc_city, zc_state, zc_zip FROM search_zipcodes WHERE zc_city LIKE '$q%' OR zc_state LIKE '$q%' OR zc_zip LIKE '$q%' GROUP BY zc_city, zc_state, zc_zip ";

编辑您可以查找有关从查询中获取结果的更多信息,但您可以尝试以下方式:

while ( $rs = mysql_fetch_assoc($rsd) ){
    $array[] = $row;
}

这会将结果填充到一个数组中,数组的每个条目都是列值的数组,并删除最后一个始终为空的。

while ( ($resultArray[] = mysql_fetch_assoc($rsd) ) || array_pop( $resultArray ) );

答案 1 :(得分:0)

要返回至少有一列匹配的行,请使用OR

SELECT zc_city AS city, zc_state AS state, zc_zip AS zip
  FROM search_zipcodes
  WHERE zc_city LIKE :city OR zc_zip=:zip

作为准备好的查询,如下所示:

// connect to the DB. Should be in its own function to isolate credentials.
$db = new PDO(...);

// get the cities. Should be in a function/method to access DB (the data access layer).
$findPlace = $db->prepare("SELECT zc_city AS city, zc_state AS state, zc_zip AS zip
      FROM search_zipcodes
      WHERE zc_city LIKE :city OR zc_zip=:zip");
$places = $findPlace->execute(array(':city' => $_REQUEST['q'] . '%', 
                                    ':zip' => $_REQUEST['q']));

// display places. Should be in a method of a view class.
?>
  <ul>
    <?php foreach ($places as $place) {
       echo "<li>$place[city], $place[state] $place[zip]</li>\n";
    } ?>
  </ul>

请注意,注释中描述了三个不同的任务。每个应该属于一个单独的类,前两个属于第三个层(数据访问层)和第三个层(架构层,如模型视图或Model-View-Controller)。