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很重要!)
答案 0 :(得分:0)
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
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;
P.S。不要为表字段使用mysql保留字(如日期)