以下查询不会返回name1
的任何值,因为它没有wp_postmeta.meta_key = 'wpcf-phone'
。我正在使用LEFT OUTER JOIN
认为它会返回name1
的结果,因为它在wp_posts
中有值,但它只是name2
的返回值,其中wp_postmeta.meta_key = 'wpcf-phone'
SELECT
wp_posts.ID,
wp_posts.post_content,
wp_posts.post_title,
wp_postmeta.meta_value AS phone
FROM
wp_posts
LEFT OUTER JOIN wp_postmeta wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id)
WHERE
wp_posts.post_type = 'solicitors' AND
wp_posts.post_status = 'publish' AND
wp_postmeta.meta_key = 'wpcf-phone' AND
(wp_posts.post_title LIKE '%name1%' OR
wp_posts.post_title LIKE '%name2%')
答案 0 :(得分:3)
您正在此行的where子句中引用外部表:
wp_postmeta.meta_key = 'wpcf-phone'
从而消除wp_postmeta.meta_key
为空的所有行,有效地将LEFT JOIN
转换为INNER JOIN
(因为NULL = 'wpcf-phone'
为false)。
您应该将条件移至联接:
SELECT
wp_posts.ID,
wp_posts.post_content,
wp_posts.post_title,
wp_postmeta.meta_value AS phone
FROM
wp_posts
LEFT OUTER JOIN wp_postmeta wp_postmeta
ON (wp_posts.ID = wp_postmeta.post_id)
AND wp_postmeta.meta_key = 'wpcf-phone'
WHERE
wp_posts.post_type = 'solicitors' AND
wp_posts.post_status = 'publish' AND
(wp_posts.post_title LIKE '%name1%' OR
wp_posts.post_title LIKE '%name2%')
答案 1 :(得分:1)
当OUTER JOIN
'无法连接'时,它会使用NULL
值填充输出中的字段。因此,您可以使用OR IS NULL
来测试此情况。因此,WHERE子句应该是这样的:
WHERE
wp_posts.post_type = 'solicitors' AND
wp_posts.post_status = 'publish' AND
(wp_postmeta.meta_key = 'wpcf-phone' OR
wp_postmeta.meta_key IS NULL) AND
(wp_posts.post_title LIKE '%name1%' OR
wp_posts.post_title LIKE '%name2%')