简体   繁体   English

SQL查询不应返回数据透视表中包含空值的行

[英]SQL query should not return rows that contain null values in pivot table

I have created a query using a pivot table to extract some metadata (from my wordpress database) for latitude and longitude values associated with posts. 我使用数据透视表创建了一个查询,以提取一些元数据(从我的wordpress数据库中)来获取与帖子相关的纬度和经度值。 I would like to only return posts that have these particular pieces of metadata, and ignore all other posts, but I am unable to filter out those posts that don't have values or these meta keys. 我只想返回具有这些特定的元数据片段的帖子,而忽略所有其他帖子,但是我无法过滤掉那些没有值或这些元键的帖子。 Here is my SQL: 这是我的SQL:

SELECT wp_posts.ID,   
wp_posts.post_title, wp_posts.post_modified_gmt,
MAX(CASE WHEN wp_postmeta.meta_key = "_wp_geo_longitude" then wp_postmeta.meta_value ELSE NULL END) as longitude,
MAX(CASE WHEN wp_postmeta.meta_key = "_wp_geo_latitude" then wp_postmeta.meta_value ELSE NULL END) as latitude
FROM wp_posts JOIN wp_postmeta  ON ( wp_postmeta.post_id = wp_posts.ID)  
WHERE wp_posts.post_status = 'publish'                  
GROUP BY wp_posts.ID, wp_posts.post_title;

I have tried adding the following to the WHERE clause with zero effect: 我尝试将以下内容添加到WHERE子句中,效果为零:

WHERE longitude IS NOT NULL
WHERE wp_postmeta.meta_value IS NOT NULL

And variations of that, but all posts are still returned, regardless of null values. 以及它的变体,但无论空值如何,仍将返回所有帖子。

Just add a having clause: 只需添加一个having子句:

having longitude is not null and latitude is not null

This is a situation where the join method of pivoting might be more efficient: 在这种情况下,透视的join方法可能更有效:

SELECT p.ID, p.post_title, p.post_modified_gmt,
       lng.meta_value as longitude, lat.meta_value as latitude
FROM wp_posts p JOIN
     wp_postmeta lat
     ON wp_postmeta.post_id = p.ID AND lat.meta_key = '_wp_geo_latiitude' JOIN
     wp_postmeta lng
     ON wp_postmeta.post_id = p.ID AND lng.meta_key = '_wp_geo_longitude'
WHERE p.post_status = 'publish';

In general, I prefer the aggregation method more than the join method because it is more flexible. 通常,我更喜欢聚合方法而不是连接方法,因为它更灵活。 However, you are only getting two fields and you want to ensure that both are there. 但是,您只得到两个字段, 并且要确保两个字段都存在。 That means that the option of using join s is quite reasonable in this case. 这意味着在这种情况下,使用join的选项是非常合理的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM