查询无法处理左连接?

时间:2014-02-19 06:06:40

标签: php mysql

我有以下查询,它给出了single marstat的结果。

SELECT
  a_event . *,
  members.*  
FROM a_event
  INNER JOIN members
    ON (members.mem_id = a_event.a_uid)
  LEFT JOIN `profiles`
    ON (profiles.mem_id = members.mem_id
        AND profiles.marstat =  'Single')
WHERE a_event.a_event_id = '5496'
    AND members.gender = 'm'
    AND a_event.a_fb_event_id = '0'

但实际情况是a_event成员必须与成员表匹配(INNER JOIN是强制性的),那么这个结果将与profile表的具有婚姻状态的mem_id匹配。但主要问题是配置文件表可能包含profiles.mem_id的结果或没有条目,以便来自a_event.mem_id的用户如果不存在于profiles.mem_id中那么该用户也将被视为single

请帮忙 感谢

2 个答案:

答案 0 :(得分:4)

如果我正确理解了您的问题,您希望在以下情况下返回一行:

a)用户有个人资料并且是单身 b)用户没有个人资料

在这种情况下,查询应为:

SELECT
  a_event . *,
  members.*  
FROM a_event
  INNER JOIN members
    ON (members.mem_id = a_event.a_uid)
  LEFT JOIN `profiles`
    ON (profiles.mem_id = members.mem_id)
WHERE a_event.a_event_id = '5496'
    AND members.gender = 'm'
    AND a_event.a_fb_event_id = '0'
    AND (profiles.marstat =  'Single' OR profiles.marstat IS NULL)

答案 1 :(得分:0)

没有小提琴它很难测试,但试试这个:用小提琴更新答案

    SELECT
      a_event . *,
      members.*  
    FROM a_event
      INNER JOIN members
        ON (members.mem_id = a_event.a_uid)
      LEFT JOIN `profiles`
        ON (profiles.mem_id = members.mem_id)
    WHERE a_event.a_event_id = '5496'
        AND members.gender = 'm'
        AND a_event.a_fb_event_id = '0'
        AND (profiles.marstat =  'Single' or is null)

http://sqlfiddle.com/#!2/99b774/3