开发者

I am having some difficulties on my wrong multiple where query

When I just let one WHERE and remove the other it returns me the correct result. When I have it as is it does not display anything. How can I write correctly my logic below?

My aim is to display only the result who satisfy the "extra1 = $value1 and extra2 = $value2 and extra3 = $value3."

I read somewhere that I have to add the addslashes. What is the use of it?

$value1 = addslash开发者_如何学编程es($_GET['extra1']);
$value2 = addslashes($_GET['extra2']);
$value3 = addslashes($_GET['extra3']);

$theposts = $wpdb->get_results("SELECT post_title FROM {$wpdb->posts}
WHERE ID IN
(
   SELECT DISTINCT post_id
   FROM {$wpdb->postmeta}
   WHERE meta_key = 'extra1' AND meta_value = '$value1'
   WHERE meta_key = 'extra2' AND meta_value = '$value2'
   WHERE meta_key = 'extra3' AND meta_value = '$value3'

)");


If your database supports intersections then you can do this:

SELECT post_id
FROM {$wpdb->postmeta}
WHERE meta_key = 'extra1' AND meta_value = '$value1' 
    INTERSECT
SELECT post_id
FROM {$wpdb->postmeta}
WHERE meta_key = 'extra2' AND meta_value = '$value2'
    INTERSECT
SELECT post_id
FROM {$wpdb->postmeta}
WHERE meta_key = 'extra3' AND meta_value = '$value3'

That will give you all the post_ids that have extra1/value1, extra2/value2, and extra3/value3.

If you don't have INTERSECT (such as, AFAIK, MySQL), you can try HAVING:

SELECT post_id
FROM {$wpdb->postmeta}
WHERE meta_key = 'extra1' AND meta_value = '$value1'
   OR meta_key = 'extra2' AND meta_value = '$value2'
   OR meta_key = 'extra3' AND meta_value = '$value3'
GROUP BY post_id
HAVING COUNT(*) = 3


Only one WHERE is possible per (sub) query. Replace subsequent WHEREs with ANDs. By the way: what is the error message saying?


Combine them with the OR keyword

 WHERE meta_key = 'extra1' AND meta_value = '$value1' 
 OR 
 meta_key = 'extra2' AND meta_value = '$value2' 
 OR
 meta_key = 'extra3' AND meta_value = '$value3'


You could also use this:

SELECT p.post_title FROM {$wpdb->posts} AS p
WHERE EXISTS
  ( SELECT *
    FROM {$wpdb->postmeta} AS pm
    WHERE pm.meta_key = 'extra1' AND pm.meta_value = '$value1' 
      AND pm.post_id = p.ID
  )
  AND EXISTS
  ( SELECT * 
    FROM {$wpdb->postmeta} AS pm
    WHERE pm.meta_key = 'extra2' AND pm.meta_value = '$value2'
      AND pm.post_id = p.ID
  )
  AND EXISTS
  ( SELECT *
    FROM {$wpdb->postmeta} AS pm
    WHERE pm.meta_key = 'extra3' AND pm.meta_value = '$value3'
      AND pm.post_id = p.ID
  )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜