SQL显示值,即使WHERE子句不正确

时间:2019-07-15 00:22:16

标签: mysql sql database

我有一个SQL查询,该输出总共输出48行,然后我添加了一些表来加入,我只得到一行作为响应,

这是我的第一个查询,总共输出48行

      SELECT
        users.uid,
        users_roles.rid,
        users.mail,
        users.name,
        dependant.field_dependent_type_tid,
        player_name.field_member_name_value
      FROM
        users
        JOIN users_roles
        JOIN field_data_field_dependent_type AS dependant
        JOIN field_data_field_member_name AS player_name
      WHERE
        users.uid = users_roles.uid
        AND users_roles.rid = 13
        AND dependant.field_dependent_type_tid != 374
        AND dependant.entity_id = users.uid
        AND player_name.entity_id = users.uid

然后当我添加手机号码字段时,输出变为1行

这是我的第二个查询,总共输出1行

    SELECT
      users.uid,
      users_roles.rid,
      users.mail,
      users.name,
      dependant.field_dependent_type_tid,
      player_name.field_member_name_value,
      mobile_number.field_mobile_number_value
    FROM
      users
      JOIN users_roles
      JOIN field_data_field_dependent_type AS dependant
      JOIN field_data_field_member_name AS player_name
      JOIN field_data_field_mobile_number AS mobile_number
    WHERE
      users.uid = users_roles.uid
      AND users_roles.rid = 13
      AND dependant.field_dependent_type_tid != 374
      AND dependant.entity_id = users.uid
      AND player_name.entity_id = users.uid
      AND mobile_number.entity_id = users.uid

如您在查询中所见,我添加了一个手机号码字段,以显示uid等于entitiy_id的{​​{1}}的用户的手机号码字段,但是48位用户中只有1位注册了其手机号码。

我要做的是显示所有这48行,其中包括具有移动电话号码的一行用户,

所以输出将是47个用户的手机号码为空,而一个用户的手机号码为空,如何在给定的查询示例中做到这一点?

1 个答案:

答案 0 :(得分:3)

更改语法以使用左联接,并将联接条件置于联接中,而不放在where子句中:

 SELECT
      users.uid,
      users_roles.rid,
      users.mail,
      users.name,
      dependant.field_dependent_type_tid,
      player_name.field_member_name_value,
      mobile_number.field_mobile_number_value
    FROM
      users
      left JOIN users_roles on users.uid = users_roles.uid AND users_roles.rid = 13
      left JOIN field_data_field_dependent_type AS dependant
   on dependant.field_dependent_type_tid != 374
     left  JOIN field_data_field_member_name AS player_name  on dependant.entity_id = users.uid
      left JOIN field_data_field_mobile_number AS mobile_number
 on player_name.entity_id = users.uid and mobile_number.entity_id = users.uid