duangouhui0446 2011-11-25 22:02
浏览 64
已采纳

带有多个AND的MySQL查询

I'm new to MySQL and I'm having problem with a query using PHP. See the three last lines.

$query = "
SELECT post_content, slug, ID
FROM wp_posts

INNER JOIN wp_term_relationships
ON wp_posts.ID = wp_term_relationships.object_id

INNER JOIN wp_terms
ON wp_term_relationships.term_taxonomy_id = wp_terms.term_id

INNER JOIN wp_postmeta
ON wp_posts.ID = wp_postmeta.post_id

WHERE post_status = 'publish' AND slug = 'a-slug' AND meta_key <> 'include' AND meta_key <> 'exkludera'
OR post_status = 'publish' AND slug = 'a-slug' AND meta_key = 'include' AND meta_value = '72'
OR post_status = 'publish' AND slug = 'a-slug' AND meta_key = 'exclude' AND meta_value <> '72'
";

With the three last lines I want to say:

Row 1) Select query if it: Is publish, Has a-slug and doesnt have meta_key "include" or "exclude"

Row 2) Select query if it: Is publish, Has a-slug, have meta_key "include" and meta_value is '72'

Row 3) Select query if it: Is publish, Has a-slug, have meta_key "exclude" and meta_value is not '72'

But it gives me back double or tripple of each select. It should only be selected if it matchhes one of these three senarios. What am I doing wrong?

  • 写回答

3条回答 默认 最新

  • douzhu1188 2011-11-25 22:04
    关注

    You need to use brackets:

    WHERE (post_status = 'publish' AND slug = 'a-slug' AND meta_key <> 'include' AND meta_key <> 'exkludera')
    OR (post_status = 'publish' AND slug = 'a-slug' AND meta_key = 'include' AND meta_value = '72')
    OR (post_status = 'publish' AND slug = 'a-slug' AND meta_key = 'exclude' AND meta_value <> '72')
    

    Just mixing OR and AND statements like you do in your example evaluates to true for all cases where post_status = 'publish'.

    By the way, I am assuming that Row 1) etc. refers to the lines in your code, not the rows you want returned from the database...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了