MySQL:为子查询分配列名/句柄

时间:2013-08-13 17:38:21

标签: mysql subquery

我正在使用MySQL开发博客网站。我正在运行一个遍及两个表的子查询。

DROP TABLE IF EXISTS `blog_entries`;
CREATE TABLE IF NOT EXISTS `blog_entries` (
    `id` int(10) unsigned NOT NULL auto_increment,
    `title` varchar(255) NOT NULL,
    `slug` varchar(255) NOT NULL,
    `live` boolean default FALSE,
    `date` datetime NOT NULL,
    `author` int(3) default 0,
    `body` text NOT NULL,
    `category` int(2) default 0,
    `tags` varchar(255) default '',
    UNIQUE KEY `id` (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS `blog_entry_comments`;
CREATE TABLE IF NOT EXISTS `blog_entry_comments` (
    `id` int(10) unsigned NOT NULL auto_increment,
    `blog_entry_id` int(10) NOT NULL,
    `live` boolean default FALSE,
    `date` datetime NOT NULL,
    `name` varchar(128) default '',
    `email` varchar(128)    default '',
    `web` varchar(128)  default '',
    `comments` text NOT NULL,
    UNIQUE KEY `id` (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

查询如下所示:

SELECT be.id, be.title, 
       (SELECT (COUNT(bec.blog_entry_id)) AS blog_entry_comments_total 
        FROM blog_entry_comments bec 
        WHERE be.id = bec.blog_entry_id), 
       (SELECT (COUNT(bec.blog_entry_id)) AS blog_entry_comments_disabled 
        FROM blog_entry_comments bec 
        WHERE be.id = bec.blog_entry_id AND bec.live = 0) 
FROM blog_entries be;

现在我认为“AS blog_entry_comments_total”和“AS blog_entry_comments_disabled”这一位会将结果列命名为相应的名称,但正如您从下面的结果中看到的那样,我将整个子查询作为列名:

| id | title | (SELECT (COUNT(bec.blog_entry_id)) AS blog_entry_comments_total FROM blog_entry_comments bec WHERE be.id = bec.blog_entry_id) | (SELECT (COUNT(bec.blog_entry_id)) AS blog_entry_comments_disabled FROM blog_entry_comments bec WHERE be.id = bec.blog_entry_id AND bec.live = 0) |

+----+----------------

|  1 | Blog Entry One | 3 | 1
|  2 | New Post | 0 | 0
|  3 | Testing | 0 | 0

3 rows in set (0.00 sec)

我需要的是一个句柄,我可以用它来引用这个列,这似乎没有提供一个合理命名的句柄。我正在寻找的是一个看起来像这样的结果集:

| id | title | blog_entry_comments_total | blog_entry_comments_disabled |

+----+----------------

|  1 | Blog Entry One | 3 | 1
|  2 | New Post | 0 | 0
|  3 | Testing | 0 | 0

3 rows in set (0.00 sec)

我有什么问题吗?

1 个答案:

答案 0 :(得分:0)

你把别名放错了地方。它应该是这样的:

SELECT be.id, be.title, 
       (SELECT (COUNT(bec.blog_entry_id))
        FROM blog_entry_comments bec 
        WHERE be.id = bec.blog_entry_id) AS blog_entry_comments_total, 
       (SELECT (COUNT(bec.blog_entry_id)) 
        FROM blog_entry_comments bec 
        WHERE be.id = bec.blog_entry_id AND bec.live = 0) AS blog_entry_comments_disabled

FROM blog_entries be;