我正在创建一个博客文章系统,我正在使用以下表格结构: -
blog_category
category_id, category_name, enabled, created_date
blog_post
post_id,title,article, author_id,date_published
post_category
category_id, post_id
blog_tag
tag_id, tag_name
post_tag
id,tag_id,post_id
post_related
id, post_id, post_related_id
blog_comment
comment_id, post_id, is_reply_to_id,comment,user_id
我的问题是:
如何在单个查询中获得此类输出
title,author_name,article,total_comments,post_tags
如何在post_related表中插入记录,以便在选择特定帖子时显示相关帖子。
我尝试这样但显示unknown column bp.post_id
CREATE PROCEDURE blog_get_posts_in_category(
IN inCategoryId INT, IN inShortPostDescriptionLength INT,
IN inPostsPerPage INT, IN inStartItem INT)
BEGIN
PREPARE statement FROM
"SELECT bp.post_id, bp.title,(select count(*) from blog_comment where post_id=bp.post_id) as total_comments,
IF(LENGTH(bp.article) <= ?,
bp.article,
CONCAT(LEFT(bp.article, ?),
'...')) AS article,
DATE_FORMAT(bp.date_published,'%d %M %Y at %h:%i:%s %p') as date_published, bp.banner_image,ba.display_name
FROM blog_post bp
INNER JOIN blog_post_to_category bpc
ON bpc.post_id = bp.post_id
INNER JOIN blog_author ba
ON ba.id = bp.author_id
WHERE bpc.category_id = ? and enabled=1
ORDER BY bp.post_id DESC
LIMIT ?, ?";
SET @p1 = inShortPostDescriptionLength;
SET @p2 = inShortPostDescriptionLength;
SET @p3 = inCategoryId;
SET @p4 = inStartItem;
SET @p5 = inPostsPerPage;
EXECUTE statement USING @p1, @p2, @p3, @p4, @p5;
END$$
答案 0 :(得分:0)
Q1:
这个问题并不是很清楚,所以我们假设这样 - blog_author表看起来像 author_id,author_name,... - total_comments是属于博客帖子的所有评论的编号。 - post_tags可以是一个字符串,其中包含与博客帖子相关的所有post_tags(例如,作为csv)。
然后,查询可以是:
SELECT
bp.post_id as pid, bp.title, a.author_name, bp.article, bc.total_comments, pt.post_tags
FROM blog_post bp
LEFT JOIN blog_author a ON bp.author_id=a.id
LEFT JOIN (
SELECT post_id, COUNT(*) as total_comments
FROM blog_comment
GROUP BY post_id) bc
ON bc.post_id=bp.post_id
LEFT JOIN (
SELECT post_id, GROUP_CONCAT(DISTINCT tag_id SEPARATOR ',') AS post_tags
FROM post_tag
GROUP BY post_id) pt
ON pt.post_id=bp.post_id;
Q2:
在这里,查询似乎没问题。我甚至自己尝试过,我没有得到关于bp.post_id的错误消息。只有一个想法可以使用我在上一个查询中显示的连接(使用blog_comment表)来避免使用total_comments的子查询。
但是这个程序/查询做的事情不同于应该提出的问题。 (它甚至没有任何对blog_related表的引用。)