0

SQL

SELECT IFNULL(parent, id) as p
FROM article_comments
WHERE article_id = 3
GROUP BY p LIMIT 8

PHP

foreach ($result AS $data)
{
    $parents .= $data['p'] . ',';
}

SQL

SELECT 
    *,
    IFNULL(parent, id) AS p,
    IFNULL(reply_comment_id, id) AS r
    FROM article_comments
WHERE IFNULL(parent, id) IN('.$parents.') AND article_id = 3
ORDER BY p ASC, r ASC, date DESC

如何在不使用 PHP 的情况下合并两个查询?(限制 8 很重要!)

4

1 回答 1

0

1.带子查询

SELECT 
    *,
    IFNULL(parent, id) AS p,
    IFNULL(reply_comment_id, id) AS r
FROM
    article_comments
WHERE
    IFNULL(parent, id) IN (
        SELECT IFNULL(parent, id)
        FROM article_comments
        WHERE article_id = 3
        GROUP BY p
        LIMIT 8
    ) AND 
    article_id = 3
ORDER BY 
    p ASC, 
    r ASC, 
    date DESC

2.带临时表

CREATE TEMPORARY TABLE _temp ( p INT(10) NULL );

INSERT INTO _temp
SELECT IFNULL(parent, id)
FROM article_comments
WHERE article_id = 3
GROUP BY p
LIMIT 8;

SELECT 
    *,
    IFNULL(parent, id) AS p,
    IFNULL(reply_comment_id, id) AS r
FROM
    article_comments
WHERE
    IFNULL(parent, id) IN (
        SELECT p
        FROM _temp
    ) AND 
    article_id = 3
ORDER BY 
    p ASC, 
    r ASC, 
    date DESC;

DROP TABLE _temp;

ps不要为你的表字段使用mysql保留字(比如日期)

于 2012-09-27T08:50:55.120 回答