I am creating a query for MYSQL that will create a table from 4 tables.
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
Which produces:
ID - first_name - last_name- church - user - shirt_size - trip_id - trip_name
3025 - firstname - lastname - 23 - 1 - Large - 2033 - NULL
These tables are basic wordpress tables coming from. I use the wp_posts table 2 times.
wp_usermeta wp_posts wp_postmeta
The problem is that I can not get the trip name to populate based on the trip_id. IE the triop_id is a post id, and I am trying to get the post title from that. That custom post type is post_mission_trip.
If I add a Where clause at the end
AND xp_2.ID IS NOT NULL
I get this as the output:
ID - first_name - last_name- church - user - shirt_size - trip_id - trip_name
3025 - NULL - NULL - NULL - NULL - NULL - 2033 - Trip Name
Just wrap the xp_2.post_title
in a MAX()
aggregate.
MAX(xp_2.post_title) AS `trip_name`
^^^^ ^
The problem is that the GROUP BY
is collapsing the rows, and you're getting a value from an indeterminate row. That's an outer join, and the join predicate is equality on an expression that can return a NULL (the CASE expression)...
The MAX()
aggregate will filter out the NULL values, and get a non-NULL value. The only way to get a NULL returned would be if all the rows had a NULL.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.