当我只让一个WHERE并删除另一个时,它会返回正确的结果。当我拥有它时,它不显示任何东西。我怎样才能正确编写下面的逻辑?
我的目标是只显示满足“extra1 = $ value1和extra2 = $ value2 and extra3 = $ value3”的结果。
我在某处读到了我必须添加 addslashes 。有什么用?
$value1 = addslashes($_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'
)");
答案 0 :(得分:1)
每个(子)查询只能有一个WHERE。用AND替换后续的WHERE。顺便问一下:错误信息是什么?
答案 1 :(得分:1)
如果您的数据库支持交叉点,那么您可以这样做:
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'
这将为您提供具有extra1 / value1,extra2 / value2和extra3 / value3的所有post_id
。
如果您没有INTERSECT
(例如,AFAIK,MySQL),您可以尝试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
答案 2 :(得分:0)
将它们与OR关键字
结合使用 WHERE meta_key = 'extra1' AND meta_value = '$value1'
OR
meta_key = 'extra2' AND meta_value = '$value2'
OR
meta_key = 'extra3' AND meta_value = '$value3'
答案 3 :(得分:0)
你也可以使用它:
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
)