如果一行已经显示,则可以跳过该行


A way to skip over a row if it has already been displayed

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

有人知道使用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

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

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

这意味着不会检索到重复的代码,从而省去了更改第二组代码的麻烦。

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

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

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

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