3

我知道不可能在嵌套的 IN 中使用限制,但我认为有办法做到这一点,我只是不确定如何。

我有一个包含评分和评论的表(为解释而简化)


我的单表: +----+------------------+------------+------------+- ----------------+ | 编号 | 评论者评论 | is_rating | parent_id | reviewer_rating | +----+------------------+------------+------------+- ----------------+ | 1 | 做得好率A | 1 | 0 | 5 星 | | 2 | 评论AonRateA | 0 | 1 | | | 3 | 评论BonRateA | 0 | 1 | | | 4 | 评论ConRateA | 0 | 1 | | | 5 | 评论DonRateA | 0 | 1 | | | 6 | 评论EonRateA | 0 | 1 | | | 7 | commentFonRateA | 0 | 1 | | | 8 | 做得好率B | 1 | 0 | 4 星 | | 9 | 做得好率C | 1 | 0 | 5 星 | | 11 | 做得好评价D | 1 | 0 | 3 星 | | 12 | 做得好率E | 1 | 0 | 2 星 | | 13 | 做得好率F | 1 | 0 | 5 星 | | 14 | 干得好率G | 1 | 0 | 3 星 | | 15 | commentAonRateD | 0 | 11 | | +----+------------------+------------+------------+- ----------------+
所以,
如果 is_rating = 1,它就是一个评级。
如果 is_rating = 0,它是对评级的评论(它的父评级是 parent_id=id 的地方)

所以这看起来像:

做得好评价A *****  
 评论AonRateA  
 评论BonRateA  
 评论ConRateA  
 评论DonRateA  
 评论EonRateA  
 评论FonRateA    
做得好评分B ****  
做得好率C *****  
做得好评价D ***  
 评论评分    
做得好率E **  
干得好F *****  
做得好评分G ***  

我想要做的是选择最新的五个评级,关联最新的 5 条评论,仅使用 1 个查询

所以,一些如何加入这两个:

SELECT ratings.*
        FROM mySingleTable as ratings
        WHERE 
        is_rating = 1
        ORDER BY timestamp DESC LIMIT 0, 5  

    SELECT comments.*
        FROM mySingleTable as comments
        Where 
        comments.parent_id = ratings.id 
        AND is_rating = 0
        ORDER BY timestamp DESC LIMIT 0, 5

第二个查询需要以某种方式了解评级查询

4

2 回答 2

1

请尝试此查询,该查询现已简化并经过测试。

SELECT *
FROM
 (SELECT *,
        IF (group_id = @prev,
            @n := @n + 1,
            @n := 1 AND @prev := group_id) as position
 FROM (
   SELECT mySingleTable.*, group_id
   FROM   mySingleTable
   INNER JOIN
       (SELECT id AS group_id
        FROM   mySingleTable
        WHERE  is_rating = 1
        ORDER BY timestamp DESC LIMIT 0, 5
       ) AS top5ratings
   ON     mySingleTable.id = group_id OR mySingleTable.parent_id = group_id
   ORDER BY group_id DESC,
            mySingleTable.parent_id ASC,
            timestamp DESC) AS all_reviews
  JOIN  (SELECT @n := 0, @prev := 0) AS setup) AS reviews
WHERE reviews.position < 7

请记住, SELECT * 是不好的做法。我用它来简化阅读。

于 2013-04-13T15:28:58.157 回答
0

试试这个查询

SELECT comments.*
FROM
(
SELECT ratings.id
        FROM mySingleTable as ratings
        WHERE 
        is_rating = 1
        ORDER BY timestamp DESC LIMIT 0, 5 ) AS Top5
INNER JOIN mySingleTable AS comments ON  comments.parent_id = Top5.id 
WHERE comments.is_rating = 0
ORDER BY comments.timestamp DESC LIMIT 0, 5
于 2013-04-13T14:03:18.853 回答