Ajax实时搜索多表结果重复,使用SELECT DISTINCT无效如何解决
问题根因
你之前使用SELECT DISTINCT不生效的核心原因是:现有逻辑是循环遍历pharmacie库下的每张表单独执行查询,DISTINCT仅能去除单张表内部的重复数据,无法处理多张表之间的重复药品记录。
修复方案
无需修改前端JS代码,仅调整后端livesearch.php逻辑即可,通过「单表预去重+全局数组记录已输出内容」的方式实现所有搜索结果唯一展示:
修改后完整后端代码
<?php /* Attempt MySQL server connection. Assuming you are running MySQL server with default setting (user 'root' with no password) */ $link = mysqli_connect("localhost", "root", "", "pharmacie"); // Check connection if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } // 初始化唯一药品记录数组,用来存已经输出过的药品名 $unique_medicines = []; // 把term判断提到循环外,避免重复判断 if(isset($_REQUEST["term"])){ $param_term = $_REQUEST["term"] . '%'; $tables = mysqli_query($link, "SHOW TABLES"); while ($table = mysqli_fetch_object($tables)) { $table_name = $table->{"Tables_in_pharmacie"}; // 只查需要的Nom_medicine字段,同时先去单表内重复 $sql = "SELECT DISTINCT Nom_medicine FROM " . $table_name . " WHERE Nom_medicine LIKE ?"; if($stmt = mysqli_prepare($link, $sql)){ // Bind variables to the prepared statement as parameters mysqli_stmt_bind_param($stmt, "s", $param_term); // Attempt to execute the prepared statement if(mysqli_stmt_execute($stmt)){ $result = mysqli_stmt_get_result($stmt); // Check number of rows in the result set if(mysqli_num_rows($result) > 0){ // Fetch result rows as an associative array while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){ $med_name = $row["Nom_medicine"]; // 仅当药品名未输出过时才打印 if(!isset($unique_medicines[$med_name])){ echo "<p>" . $med_name . "</p>"; // 标记为已输出 $unique_medicines[$med_name] = true; } } } } else{ echo "ERROR: Could not able to execute $sql. " . mysqli_error($link); } // Close statement mysqli_stmt_close($stmt); } } } // close connection mysqli_close($link); ?>
逻辑说明
- 提前初始化空数组
$unique_medicines,用于全局记录已经输出过的药品名称 - 单表查询时使用
SELECT DISTINCT Nom_medicine替代SELECT *,先过滤单表内的重复药品,同时仅查询需要的字段,减少无效数据传输,提升查询性能 - 输出药品名称前先判断是否已存在于记录数组中,仅未出现过的内容才会输出并添加到记录数组,彻底消除跨表重复的问题
内容的提问来源于stack exchange,提问作者Night Fall
相关产品推荐
相关产品推荐

