结合查询

时间:2012-01-27 14:36:18

标签: mysql

尝试保存一个步骤并将这两个查询结合起来但不确定如何最好地解决它。基本上第一个查询是获取我们系统中的评论列表,第二个查询是否已发送通知(如果有结果返回则已发送)。

获得评论:

SELECT r.*, 
    coalesce( ( SELECT AVG(rr.rating) 
                FROM `" . DBTABLEPREFIX . "reviews_ratings` rr 
                WHERE rr.review_id = r.id
              )
            , ''
            ) AS rating,
    FROM `" . DBTABLEPREFIX . "reviews` r
    WHERE BELOW SELECT IS 0 RESULTS

检查通知是否存在(是的,我知道这不起作用):

SELECT rn.* 
FROM `" . DBTABLEPREFIX . "reviews_notifications` rn 
WHERE rn.website_id = r.website_id 
  AND rn.post_id = r.post_id

有关正确方法的任何想法吗?如果您想知道为什么我们无法检查通知表上的r.id,因为每天都会使用新数据清除review和reviews_ratings表。该过程可能会在以后重写,不会被杀,只会添加新项目。

1 个答案:

答案 0 :(得分:1)

您可以使用NOT EXISTS

使用相关子查询
SELECT r.*, 
    coalesce( ( SELECT AVG(rr.rating) 
                FROM `" . DBTABLEPREFIX . "reviews_ratings` rr 
                WHERE rr.review_id = r.id
              )
            , ''
            ) AS rating,
    FROM `" . DBTABLEPREFIX . "reviews` r
    WHERE NOT EXISTS
          ( SELECT rn.* 
            FROM `" . DBTABLEPREFIX . "reviews_notifications` rn 
            WHERE rn.website_id = r.website_id 
              AND rn.post_id = r.post_id
          )

可以将其他子查询移动到FROM部分:

SELECT 
    r.*, 
    coalesce( rr.rating, '' ) AS rating,
FROM `" . DBTABLEPREFIX . "reviews` r
    LEFT JOIN
        ( SELECT
              rr.review_id, 
              AVG(rr.rating) AS rating
          FROM `" . DBTABLEPREFIX . "reviews_ratings` rr 
          GROUP BY rr.review_id
        ) AS rr
      ON rr.review_id = r.id     
WHERE NOT EXISTS
      ( SELECT rn.* 
        FROM `" . DBTABLEPREFIX . "reviews_notifications` rn 
        WHERE rn.website_id = r.website_id 
          AND rn.post_id = r.post_id
      )