两个内连接和第一个子句的位置

时间:2012-08-13 13:19:55

标签: mysql sql

我有以下SQL:

SELECT * FROM wp_postmeta 
INNER JOIN wp_term_relationships ON wp_postmeta.post_id = wp_term_relationships.object_id AND wp_term_relationships.term_taxonomy_id = '10' 
INNER JOIN wp_posts ON wp_postmeta.post_id = wp_posts.id WHERE wp_posts.post_date BETWEEN CONCAT(CURDATE(),' 10:00:00') AND CONCAT(CURDATE(),' 18:00:00')
WHERE wp_postmeta.meta_key = '_shipping_country' AND wp_postmeta.meta_value IN ('AU', 'US', 'JP', 'BR', 'UK')
ORDER BY wp_postmeta.post_id DESC

为什么它不起作用的任何原因,但如果我删除第二个INNER JOIN它工作正常?

4 个答案:

答案 0 :(得分:2)

您不能在内部联接条件中拥有WHERE

SELECT * FROM wp_postmeta 

INNER JOIN wp_term_relationships ON wp_postmeta.post_id = wp_term_relationships.object_id AND wp_term_relationships.term_taxonomy_id = '10' 
INNER JOIN wp_posts ON wp_postmeta.post_id = wp_posts.id AND wp_posts.post_date BETWEEN CONCAT(CURDATE(),' 10:00:00') AND CONCAT(CURDATE(),' 18:00:00')
WHERE wp_postmeta.meta_key = '_shipping_country' AND wp_postmeta.meta_value IN ('AU', 'US', 'JP', 'BR', 'UK')
ORDER BY wp_postmeta.post_id DESC

答案 1 :(得分:0)

你有两个'WHERE'语句。这可能是一个问题:)

答案 2 :(得分:0)

是的:虽然可能有一些wp_postmeta具有相应的wp_term_relationships,而另一些wp_posts却有LEFT JOIN,但没有一个同时拥有{{1}}。

要详细了解您的数据,请将联接更改为{{1}}

答案 3 :(得分:0)

同一个查询中不能有两个WHERE子句。

您需要做的就是将第一个WHERE条件移动到现有子句中,或者只将其设为AND加入:

或者:

SELECT * FROM wp_postmeta 
INNER JOIN wp_term_relationships ON wp_postmeta.post_id = wp_term_relationships.object_id AND wp_term_relationships.term_taxonomy_id = '10'  
INNER JOIN wp_posts ON wp_postmeta.post_id = wp_posts.id AND wp_posts.post_date BETWEEN CONCAT(CURDATE(),' 10:00:00') AND CONCAT(CURDATE(),' 18:00:00') 
WHERE wp_postmeta.meta_key = '_shipping_country' AND wp_postmeta.meta_value IN ('AU', 'US', 'JP', 'BR', 'UK') 
ORDER BY wp_postmeta.post_id DESC 

或者:

SELECT * FROM wp_postmeta       
INNER JOIN wp_term_relationships ON wp_postmeta.post_id = wp_term_relationships.object_id AND wp_term_relationships.term_taxonomy_id = '10'  
INNER JOIN wp_posts ON wp_postmeta.post_id = wp_posts.id 
WHERE wp_postmeta.meta_key = '_shipping_country' AND wp_postmeta.meta_value IN ('AU', 'US', 'JP', 'BR', 'UK') 
AND wp_posts.post_date BETWEEN CONCAT(CURDATE(),' 10:00:00') AND CONCAT(CURDATE(),' 18:00:00') 
ORDER BY wp_postmeta.post_id DESC