目前,我正在运行此 SQL 查询来检索商店定位器的自定义帖子。一切都很好,除了我希望它返回项目,即使“电话”字段为空。截至目前,它只会拉入已填写该字段的内容。
这是我的查询运行时的样子:
有人知道吗? (还有更有效的方法来运行它吗?)
SELECT wp_posts.post_title as name,
address.meta_value as address,
latitude.meta_value as lat,
longitude.meta_value as lng,
telephone.meta_value as phone,
( 3959 * acos(
cos( radians( '%s' ) ) *
cos( radians( CONVERT( latitude.meta_value, DECIMAL( 10, 6 ) ) ) ) *
cos( radians( CONVERT( longitude.meta_value, DECIMAL( 10, 6 ) ) ) - radians( '%s' ) ) +
sin( radians( '%s' ) ) * sin( radians( CONVERT( latitude.meta_value, DECIMAL( 10, 6 ) ) ) )
) ) AS distance
FROM wp_postmeta as address, wp_postmeta as latitude, wp_postmeta as longitude, wp_postmeta as telephone,
wp_posts
WHERE
(wp_posts.ID = address.post_id
AND address.meta_key = '_dealer_address' )
AND (wp_posts.ID = latitude.post_id
AND latitude.meta_key = '_dealer_latitude' )
AND (wp_posts.ID = longitude.post_id
AND longitude.meta_key = '_dealer_longitude' )
AND (wp_posts.ID = telephone.post_id
AND telephone.meta_key = '_dealer_telephone' )
最佳答案
根据 Marc B 在评论中的建议发布答案。
SELECT wp_posts.post_title as name,
address.meta_value as address,
latitude.meta_value as lat,
longitude.meta_value as lng,
telephone.meta_value as telephone,
( 3959 * acos(
cos( radians( '%s' ) ) *
cos( radians( CONVERT( latitude.meta_value, DECIMAL( 10, 6 ) ) ) ) *
cos( radians( CONVERT( longitude.meta_value, DECIMAL( 10, 6 ) ) ) - radians( '%s' ) ) +
sin( radians( '%s' ) ) * sin( radians( CONVERT( latitude.meta_value, DECIMAL( 10, 6 ) ) ) )
) ) AS distance
FROM wp_posts
LEFT JOIN wp_postmeta AS address ON(
wp_posts.ID = address.post_id
AND address.meta_key = '_dealer_address'
)
LEFT JOIN wp_postmeta AS latitude ON(
wp_posts.ID = latitude.post_id
AND latitude.meta_key = '_dealer_latitude'
)
LEFT JOIN wp_postmeta AS longitude ON(
wp_posts.ID = longitude.post_id
AND longitude.meta_key = '_dealer_longitude'
)
LEFT JOIN wp_postmeta AS telephone ON(
wp_posts.ID = telephone.post_id
AND telephone.meta_key = '_dealer_telephone'
)
WHERE wp_posts.post_type = 'dealers' HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20
关于mysql - 即使字段为空,如何运行 SQL 查询来返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5983143/