用几个LEFT JOIN查询,得不到想要的结果

时间:2014-08-18 21:00:03

标签: mysql sql left-join

这里是sql fiddle

有谁能告诉我如何使用LEFT JOIN获得此输出?

 notification_recipient  pm_sender    msg     modification_page_id 
 Peter                   Tom          Hello   NULL
 notification_recipient  pm_sender    msg     modification_page_id 
 Peter                   NULL         NULL    2

这是我尝试过的查询:

   SELECT u.name AS notification_recipient,us.name AS pm_sender,
          p.msg,um.page_id AS modification_page_id 
    FROM notification n 
    LEFT JOIN pm p ON p.pm_id = n.pm_id
    LEFT JOIN users u ON u.user_id = p.recipent_id
    LEFT JOIN users us ON us.user_id = p.sender_id
    LEFT JOIN user_modification um ON um.modification_id = n.modification_id
    WHERE u.name = 'Peter'
    AND n.is_read = '0'  

我正在寻找一些条件连接,这意味着根据字段中是否存在值来连接不同的表,但我找不到可以在我的示例中使用的表。任何其他有效的解决方案也将受到赞赏。

背景:

我打算建立一个向用户发送不同类型消息的通知系统(用户之间的私人消息,他们对条目的修改已被批准的消息等)。 当用户登录时,我想进行查询以查明该用户是否有任何未读通知。如果是,将通过Ajax向他发送通知。

为了说明,假设Tom已向Peter发送了一条私人消息,并且他对某个条目的修改已获批准,将调用表pmuser_modification中的两个触发器,以便将两个新行添加到{ {1}}。列notificationpm_id引用,pmmodification_id引用。 modification默认为is_read为未读。

这是表格架构:

0

如果用户David登录,这里是我想要通知的输出。每种消息类型的每一行。

CREATE TABLE notification
    (`id` int, `modification_id` int,`pm_id` int,`is_read` int)
;

INSERT INTO notification
    (`id`,`modification_id`,`pm_id`,`is_read`)
VALUES
    (1,1,NULL,0),
    (2,NULL,1,0),
    (3,2,NULL,0)
;

CREATE TABLE user_modification
    (`modification_id` int, `user_id` int,`page_id` int, `is_approved` int)
;

INSERT INTO user_modification
    (`modification_id`,`user_id`,`page_id`,`is_approved`)
VALUES
    (1,1,5,1),
    (2,2,2,1),
    (3,3,3,0)

;

CREATE TABLE pm
    (`pm_id` int, `sender_id` int,`recipent_id` int,`msg` varchar(200))
;

INSERT INTO pm
    (`pm_id`,`sender_id`,`recipent_id`,`msg`)
VALUES
    (1,1,2,'Hello');

CREATE TABLE users
    (`user_id` int, `name`varchar(20))
;

INSERT INTO users
    (`user_id`,`name`)
VALUES
    (1,'Tom'),
    (2,'Peter'),
    (3,'David')
;

给彼得的通知将是这样的:

 notification_recipient  pm_sender    msg     modification_page_id 
 Peter                   Tom          Hello   NULL
 notification_recipient  pm_sender    msg     modification_page_id 
 Peter                   NULL         NULL    2

1 个答案:

答案 0 :(得分:1)

此查询应该完成这项工作。这是SQLFiddle

SELECT
  n.id,
  IF(pmu.name IS NULL, pmm.name, pmu.name) recipient, 
  pmus.name sender, pm.msg, m.modification_id
FROM
  notification n
  LEFT JOIN user_modification m ON (n.modification_id = m.modification_id)
  LEFT JOIN pm ON (n.pm_id = pm.pm_id)
  LEFT JOIN users pmu ON (pm.recipent_id = pmu.user_id)
  LEFT JOIN users pmus ON (pm.sender_id = pmus.user_id)
  LEFT JOIN users pmm ON (m.user_id = pmm.user_id)
WHERE
  (pmu.name = 'Peter' OR 
     pmm.name = 'Peter') AND
  n.is_read = 0;