在一个查询中从2个表中获取数据

时间:2014-05-16 22:58:25

标签: mysql sql

我正在尝试检索通知系统的数据。我有三张桌子。一个表(通知)保存通知本身的实际信息。我有两个其他表来跟踪谁获得某些通知。有两种类型的通知,用户和全局。全局通知发送给所有用户,而用户通知仅发送给特定用户。为此,我有两个表,notifications_users和notifications_global。表格结构如下:

  • 通知(id,title,url,start,end)
  • notifications_users(notification_id,user_id,已查看)
  • notifications_global(notification_id,user_id,已查看)

我想要做的是从notification_users和notifications_global表中获取通知标题和url(来自通知表)以及查看到特定用户的所有通知的值。 UNION查询是否是最佳选择?我想只是分离查询,但后来我有两个不同的数组在我的PHP脚本中循环,我不想要。必须有一种方法可以通过一个查询将所有这些数据集中到一个数组中。以下给我一个空集:

SELECT notification.title, notification.url
FROM notifications
    RIGHT JOIN notifications_users ON notifications.id = notifications_users.notification_id 
    RIGHT JOIN notifications_global ON notifications.id = notifications_global.notification_id 
WHERE notifications_users.user_id = 11508 AND notifications_global.user_id = 11508;

2 个答案:

答案 0 :(得分:0)

SELECT a.title, a.url, b.viewed as 'User View', c.viewed as 'Global View'
FROM Notifications a
INNER JOIN Notifications_Users b
ON a.id = b.notification_id 
INNER JOIN Notifications_Global c
ON b.notification_id = c.notification_id
WHERE b.user_id = 11508 and c.user_id = 11508

答案 1 :(得分:0)

我想我可能会过度复杂一点。我只是为每个表分别编写了两个查询,然后将UNION放在它们之间。如果有人有兴趣,这就是我最终的目标。

(SELECT notification_id, notification_title, notification_url,  tbl_notifications_users_lookup.viewed
FROM tbl_notifications 
INNER JOIN tbl_notifications_users_lookup ON tbl_notifications.id = tbl_notifications_users_lookup.notification_id 
WHERE tbl_notifications_users_lookup.user_id = 11508)
UNION
(SELECT notification_id, notification_title, notification_url, tbl_notifications_global_lookup.viewed
FROM tbl_notifications 
INNER JOIN tbl_notifications_global_lookup ON tbl_notifications.id = tbl_notifications_global_lookup.notification_id 
WHERE tbl_notifications_global_lookup.user_id = 11508);
相关问题