2014-05-16 2 views
0

알림 시스템 용 데이터를 검색하려고합니다. 나는 세 개의 테이블을 가지고있다. 하나의 테이블 (알림)은 알림 자체에 대한 실제 정보를 보유합니다. 나는 누가 어떤 통보를 받았는지 추적 할 두 개의 다른 테이블을 가지고있다. 사용자와 글로벌의 두 가지 유형의 알림이 있습니다. 글로벌 알림은 모든 사용자에게 전달되는 반면 사용자 알림은 특정 사용자에게만 전달됩니다. 이를 위해 notifications_users와 notifications_global 테이블이 두 개 있습니다. 테이블 구조는 다음과 같습니다 :하나의 쿼리에서 두 테이블의 데이터 가져 오기

  • 통지 (ID, 제목, URL, 시작, 종료)
  • notifications_users (notification_id이 USER_ID가 볼)
  • notifications_global을 (notification_id이 USER_ID가 볼)

내가 원하는 것은 notifications_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; 
+0

예,이 작업을 수행하는 올바른 방법은 UNION입니다. – Barmar

+0

참고로, SO에서 "RIGHT JOIN"에 대한 MySQL 태그 아래의 검색은 현재 ca를 반환합니다. 1400 결과 - ca. LEFT JOIN에 대한 32000 개의 결과. 그냥 선생님. – Strawberry

+0

'notifications_global'이 모든 사용자에게 연결되면'user_id' 열이있는 이유는 무엇입니까? – Barmar

답변

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); 
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 
+0

이 쿼리로 빈 결과 집합이 나타납니다. 조인을 시도해 볼 것입니다. 도와 주셔서 감사합니다. – WebDev84

관련 문제