简体   繁体   English

Mysql Left OUTER JOIN与子查询(wordpress)

[英]Mysql Left OUTER JOIN with Subquery (wordpress)

I am creating a query for MYSQL that will create a table from 4 tables. 我正在为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

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. 这些表是基本的wordpress表。 I use the wp_posts table 2 times. 我使用wp_posts表2次。

wp_usermeta wp_posts wp_postmeta wp_usermeta wp_posts wp_postmeta

The problem is that I can not get the trip name to populate based on the trip_id. 问题是我无法根据trip_id获取旅行名称。 IE the triop_id is a post id, and I am trying to get the post title from that. IE浏览器的triop_id是一个职位ID,我试图从中获取职位标题。 That custom post type is post_mission_trip. 该自定义帖子类型为post_mission_trip。

If I add a Where clause at the end 如果我在末尾添加Where子句

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. 只需将xp_2.post_title包装在MAX()聚合中即可。

  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. 问题是GROUP BY正在折叠行,并且您从不确定的行中获取值。 That's an outer join, and the join predicate is equality on an expression that can return a NULL (the CASE expression)... 那是一个外部联接,联接谓词是一个相等的表达式,该表达式可以返回NULL(CASE表达式)...

The MAX() aggregate will filter out the NULL values, and get a non-NULL value. MAX()聚合将滤除NULL值,并获得非NULL值。 The only way to get a NULL returned would be if all the rows had a NULL.) 获取所有返回的NULL的唯一方法是所有行都为NULL。)

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

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