我正在为MYSQL创建一个查询,该查询将从4个表创建一个表。
SELECT xp.ID,
MAX((CASE WHEN (xum.meta_key = 'first_name') THEN xum.meta_value ELSE NULL END)) AS `first_name`,
MAX((CASE WHEN (xum.meta_key = 'last_name') THEN xum.meta_value ELSE NULL END)) AS `last_name`,
MAX((CASE WHEN (xum.meta_key = 'user_church') THEN xum.meta_value ELSE NULL END)) AS `church`,
MAX((CASE WHEN (xpm.meta_key = 'reg_user') THEN xpm.meta_value ELSE NULL END)) AS `user`,
MAX((CASE WHEN (xpm.meta_key = 'shirt_size') THEN xpm.meta_value ELSE NULL END)) AS `shirt_size`,
MAX((CASE WHEN (xpm.meta_key = 'reg_trip') THEN xpm.meta_value ELSE NULL END)) AS `trip_id`,
xp_2.post_title AS 'trip_name',
FROM xs_posts AS xp
LEFT OUTER JOIN xs_postmeta AS xpm ON xp.ID = xpm.post_id
LEFT OUTER JOIN xs_usermeta AS xum ON xum.user_id = (CASE WHEN (xpm.meta_key = 'reg_user') THEN xpm.meta_value ELSE NULL END )
LEFT OUTER JOIN xs_posts xp_2 ON xp_2.ID = (CASE WHEN (xpm.meta_key = 'reg_trip') THEN xpm.meta_value ELSE NULL END )
Where xp.post_type = 'trip_reg'
GROUP BY xp.ID
产生:
ID - first_name - last_name- church - user - shirt_size - trip_id - trip_name
3025 - firstname - lastname - 23 - 1 - Large - 2033 - NULL
这些表是来自的基本wordpress表。我使用wp_posts表2次。
wp_usermeta wp_posts wp_postmeta
问题是我无法根据trip_id获取行程名称。 IE浏览器triop_id是一个帖子ID,我正试图从中获取帖子标题。该自定义帖子类型是post_mission_trip。
如果我在末尾添加Where子句
AND xp_2.ID IS NOT NULL
我将此作为输出:
ID - first_name - last_name- church - user - shirt_size - trip_id - trip_name
3025 - NULL - NULL - NULL - NULL - NULL - 2033 - Trip Name
答案 0 :(得分:0)
将xp_2.post_title
包裹在MAX()
聚合中。
MAX(xp_2.post_title) AS `trip_name`
^^^^ ^
问题是GROUP BY
正在折叠行,并且您从不确定的行中获取值。这是一个外部联接,并且连接谓词在表达式上是相等的,可以返回NULL(CASE表达式)......
MAX()
聚合将过滤掉NULL值,并获得非NULL值。返回NULL的唯一方法是,如果所有行都为NULL。)