dqwh1208 2014-03-15 01:11
浏览 45
已采纳

从PHP mySQL搜索结果中排除值

I have read up on excluding results in PHP and mySQL but I can't seem to figure out the correct syntax for the search code I am using.

In all of my other result tables that simply pull information from the database without having to use a search form, excluding userlevels has been easily achieved by simply including the following after the "WHERE" statement:

WHERE `userlevel` !='9' AND `userlevel` !='1' AND `userlevel` !='4' AND `userlevel` !='5' AND `userlevel` !='6'

Now, I'm using a search code that uses "OR" instead of "AND" and "LIKE" with the terms. It looks like this:

//Set the MySQL query
if ($search == NULL or $search == '%'){
} else {
for ($i=0; $i<count($keywords); $i++) {
$query = "SELECT * FROM sound_users " .
"WHERE genre LIKE '%".$keywords[$i]."%'".
" OR genre2 LIKE '%".$keywords[$i]."%'" .
" OR genre3 LIKE '%".$keywords[$i]."%'" .
" OR bandname LIKE '%".$keywords[$i]."%'" .
" ORDER BY genre";

}

I saw in some other forums that "NOT IN (SELECT *)...." is being used to exclude data but it seems like every code uses punctuation differently - has a different syntax - so I'm not so sure how to exclude specific values with this search code.

I have tried simple angles like:

" OR userlevel !='5'" .
" OR userlevel !='9'" .

and that only did funky things to the search results which wound up including both of those userlevels at the same time in two different tables stacked on top of eachother. So I changed the "OR" to "AND" - like it is in my other code and that didn't work either.

At that point, I tried to add the "NOT IN" and "NOT EXISTS" examples I found but any way I do it, always seems to come back with san error telling me to check the syntax.

I'm wondering if it's even possible to exclude specific values from search results using "OR" or if exclusion only works for basic code simply calling values from the database to display and not necessarily using a search form.

  • 写回答

1条回答 默认 最新

  • doucou1892 2014-03-15 01:16
    关注

    Parentheses are your friend!

    WHERE 
      (X LIKE '%X%' OR Y LIKE '%Y%' OR Z LIKE '%Z%')
      AND
      (X NOT LIKE '%XX%' OR Y<>'abc' OR LENGTH(Z)<5 OR A<>7)
    

    BTW: The usual notation for unequality in SQL is <>, not !=

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法