MySQL LEFT JOIN不为缺失的行返回NULL

时间:2018-12-27 10:58:33

标签: mysql left-join

我可能搞砸了。但是我有一个WordPress系统,试图在MySQL中构建特定用户数据的导出。 我期望如果该行不存在,则元数据将返回NULL,但相反,它看起来像是一个限制。如果不存在任何元数据,则将忽略整个用户。

SELECT
  users.ID,
  users.user_email,
  _first.meta_value as firstName,
  _second.meta_value as lastName,
  users.display_name,
  _gender.meta_value as gender,
  _age.meta_value as age,
  _nationality.meta_value as nationality

FROM kp_users

LEFT JOIN usermeta as _first ON kp_users.id = _first.user_id
LEFT JOIN usermeta as _second ON kp_users.id = _second.user_id
LEFT JOIN usermeta as _gender ON kp_users.id = _gender.user_id
LEFT JOIN usermeta as _age ON kp_users.id = _age.user_id
LEFT JOIN usermeta as _nationality ON kp_users.id = _nationality.user_id

WHERE
  _first.meta_key = 'first_name' AND
  _second.meta_key = 'last_name' AND
  _gender.meta_key = '_user_demographics_gender' AND
  _age.meta_key = '_user_demographics_age' AND
  _nationality.meta_key = '_user_demographics_nationality'

因此,对于其中_user_demographics_age行不存在的元数据行,最终结果集将省略整个用户,而且我一生都无法弄清楚为什么。

3 个答案:

答案 0 :(得分:1)

您需要将其他条件放在ON子句中,而不是如下所示的Where子句-

SELECT
  users.ID,
  users.user_email,
  _first.meta_value as firstName,
  _second.meta_value as lastName,
  users.display_name,
  _gender.meta_value as gender,
  _age.meta_value as age,
  _nationality.meta_value as nationality

FROM kp_users

LEFT JOIN usermeta as _first ON kp_users.id = _first.user_id and _first.meta_key = 'first_name'
LEFT JOIN usermeta as _second ON kp_users.id = _second.user_id and _second.meta_key = 'last_name'
LEFT JOIN usermeta as _gender ON kp_users.id = _gender.user_id and _gender.meta_key = '_user_demographics_gender'
LEFT JOIN usermeta as _age ON kp_users.id = _age.user_id and _age.meta_key = '_user_demographics_age'
LEFT JOIN usermeta as _nationality ON kp_users.id = _nationality.user_id and _nationality.meta_key = '_user_demographics_nationality'

答案 1 :(得分:0)

将左连接表的“ where”条件移到相对的“ on”条件。目前,您获取的是空字段,但随后您的where条件正在将其过滤掉,因为_first.meta_key为空,并且不等于'firsst_name,

答案 2 :(得分:0)

将所有过滤器从where移至left join

LEFT JOIN usermeta as _first ON kp_users.id = _first.user_id and _first.meta_key = 'first_name' LEFT JOIN usermeta as _second ON kp_users.id = _second.user_id and _second.meta_key = 'last_name' -- etc.

如果左联接表在查询的left join部分具有条件(这是一个近似值,则有其他规则),MySQL优化程序会将join更改为where