我正在创建一个博客使用php和sql,我试图查询一切在1 sql查询,这样我可以带出所有的评论与作者和所有的博客与作者。他们每个人都有 user.uuid
作为外键。
我的博客表如下所示:
CREATE TABLE `blogs` (
`uuid` int(255) NOT NULL,
`title` varchar(1024) NOT NULL,
`detail` varchar(1024) NOT NULL,
`user_id` int(255) NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
我的博客评论表如下所示:
CREATE TABLE `blogs_comments` (
`uuid` int(255) NOT NULL,
`blog_uuid` int(255) NOT NULL,
`user_uuid` int(255) NOT NULL,
`comment` varchar(250) NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
我的用户表如下所示:
CREATE TABLE `users` (
`uuid` int(255) NOT NULL,
`username` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
`foreName` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`surName` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`email` text COLLATE utf8_unicode_ci NOT NULL,
`number` int(11) NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`is_admin` tinyint(1) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
以下是我当前的sql:
SELECT
b.uuid AS 'Blog ID', b.title AS 'Blog Title', b.detail AS 'Blog Body', u.uuid AS 'Blog Author ID', u.username AS 'Blog Author Username',
(SELECT bc.comment WHERE u.uuid = bc.user_uuid) AS 'Comment',
(SELECT u.uuid WHERE u.uuid = bc.user_uuid) AS 'Comment Author ID',
(SELECT u.username WHERE u.uuid = bc.user_uuid) AS 'Comment Author Username'
FROM blogs b
INNER JOIN blogs_comments bc ON b.uuid = bc.blog_uuid
INNER JOIN users u ON b.user_id = u.uuid
查询工作正常,但有意外输出,如下所示:
我希望输出有评论作者在1行中的所有评论,那么每一行将是特定的评论作者。即:
Comment Author Comment Comment
Jaquarh TEST Lorem Ipsum
1条答案
按热度按时间h22fl7wq1#
你需要知道每次你会有多少评论,但如果你知道,一个轴心可能会给你你需要的。我对您的查询结构有点困惑,但我认为它可能看起来像这样,带有一个轴:
这篇文章也可能对您有所帮助:https://docs.microsoft.com/en-us/sql/t-sql/queries/from-using-pivot-and-unpivot?view=sql-server-2017