dongling0519 2009-06-30 23:25
浏览 46
已采纳

过于具体的mysql查询无法正常工作

I have written a query to find similar ids based on tags from a current id, much like amazons, you would also like. The problem is, in my example I want to exclude bookid 30 from this search.

Here is my query:

note: $similar is basically a string filled with tags built up with a few "like %item% or"

$query = "SELECT * FROM books
          WHERE bookid !=30
          AND {$similar}
          AND visible ='1'
          AND level ='2'
          LIMIT 3";

The part that is not working is where bookid!= I've tried IS NOT, <> reordering and what ever else I could find. This query still works it outputs three rows but still includes bookid 30

Can someone explain what is going here? is my query becoming too intricate and need to be restructured?

The poor alternative i've came up with was making the limit 4 items sending it to a while loop to fetch each row and exclude the bookid i don't need. This just seems pointless when I know it can be done in the query.

Ive fixed this by rebuilding my query and $similar string Before

SELECT * FROM books WHERE bookid !=30 AND tags LIKE '%one%' OR tags LIKE '% two%' OR tags LIKE '% three%' AND visible ='1' AND level ='2' LIMIT 3

After

SELECT * FROM books WHERE bookid !=30 AND (bookid!=30 AND tags LIKE '%one%') OR (bookid!=30 AND tags LIKE '% two%') OR (bookid!=30 AND tags LIKE '% three%') AND visible ='1' AND level ='2' LIMIT 3

One thing I did notice which is strange is bookid!= only works when there is one at the beginging and between each like or... i tried swaping each out and the query would not run, but current string works perfectly!

Thanks,

  • 写回答

1条回答 默认 最新

  • dongniuxia8650 2009-06-30 23:29
    关注

    Make sure that your $similar variables are wrapped in parentheses.

    if an OR is in the middle, it will be evaluated as

    (bookid != 30 AND item like '%item1%') OR (item like '%item2%' AND visible = 1 AND level= 2)
    

    instead of

    bookid != 30 AND (item like '%item1%' OR item like '%item2%') AND visible = 1 AND level= 2
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看