0

我有一个搜索脚本,它从一个表中检索一个整数并使用它来搜索第二个表的 ID。我的问题是如果 Table1 中的整数出现不止一次,我在查询 Table2 时会得到重复的结果。

有谁知道使用 SQL 或 PHP 的方法,这样如果一行已经显示,它将跳过它?谢谢

我的代码相当复杂,但如果它有帮助的话:

//TV FILTERS
$sql = 'SELECT * FROM `table1`';
$where = array();
if ($searchlocation !== 'Any') $where[] = '`value` LIKE "%'.$searchlocation.'%"';
if ($searchmake !== 'Any')  $where[] = '`value` LIKE "%'.$searchmake.'%"';
if ($searchtype !== 'Any') $where[] = '`value` LIKE "%'.$searchtype.'%"';
if (count($where) > 0) {
  $sql .= ' WHERE '.implode(' OR ', $where);
} else {
  // Error out; must specify at least one!
}

$tvqresult = mysql_query($sql);
$num_rowstvq = mysql_num_rows($tvqresult);
while ($rowtvq = mysql_fetch_array($tvqresult)) {
$contid =  $rowtvq['contentid'];

//MAIN QUERY
$mainsql = 'SELECT * FROM `table2` WHERE `content` LIKE "%' . $searchterm . '%" AND `id` = ' . $rowtvq['contentid'] . '  AND `template` = 12';

$resultmain = mysql_query($mainsql);

$num_rowsmain = mysql_num_rows($resultmain);
if (!$resultmain) {
continue;
}

else {
while ($row = mysql_fetch_array($resultmain )) {
  echo "[!Ditto? &parents=`134` &documents=" . $row['id'] . "&tpl=`usedtempchunk`!]";
}//END MAIN LOOP

}//END MAIN ELSE

}//END TV WHILE LOOP
4

2 回答 2

1

您似乎只使用了contentid第一个查询中的列,因此您可以将其更改为:

$sql = 'SELECT distinct contentid FROM `table1`'; // rest would be the same

这意味着不会检索到任何重复项,从而为您节省更改第二组代码的麻烦。

如果您在代码中的其他位置使用第一个查询中的其他列,只要没有重复的 ID,您仍然可以使用此方法获取更多列:

$sql = 'SELECT distinct contentid, contentTitle, contentThing FROM `table1`';

如果您必须在原始查询中重复 ID,我认为您必须将数据存储在一个变量(如数组)中,然后确保第二个数据集没有重复任何内容。

于 2012-09-14T01:56:49.967 回答
0

听起来你只是在寻找 1 行,如果是这样,那么在你的 SQL 末尾,只需添加LIMIT 1. 这将确保您只返回 1 行,从而忽略任何重复的匹配项。

于 2012-09-14T01:59:42.990 回答