带有LEFT JOIN结果的UPDATE表

时间:2014-01-03 23:30:25

标签: mysql sql count sql-update

我需要一些mysql中的查询帮助,这是情况:

我有2个表,“短语”和“作者”,我需要插入每个作者在phrase_qt字段上的短语数量,使用此查询,我得到每个短语的数量:

SELECT a.name, COUNT( p.author_id ) 
FROM authors a
LEFT JOIN phrases p ON a.id = p.author_id
GROUP BY a.name, p.author_id

我给了我这个结果:

+-------------------+------------------+
|name               |COUNT(p.author_id)|
+-------------------+------------------+
|Albert Einstein    |12                |
|Bill Gates         |10                |
+-------------------+------------------+

那么如何进行查询以将每个作者的“phrase_qt”字段更新为COUNT个结果?

非常感谢你 Renan的

编辑==(显示创建表格)

显示创建表作者

CREATE TABLE `authors` (
 `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Author id',
 `thumbnail` varchar(100) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Author thumbnail image',
 `name` varchar(64) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Author name',
 `history` longtext COLLATE utf8_unicode_ci NOT NULL COMMENT 'Author history',
 `phrases_qt` int(11) NOT NULL,
 PRIMARY KEY (`id`),
 UNIQUE KEY `name` (`name`),
 KEY `id` (`id`),
 KEY `id_2` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

显示创建表短语

CREATE TABLE `phrases` (
 `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Phrase ID',
 `text` varchar(250) COLLATE utf8_unicode_ci NOT NULL COMMENT 'The phrase',
 `author_id` int(11) NOT NULL COMMENT 'Author ID',
 PRIMARY KEY (`id`),
 UNIQUE KEY `phrase` (`text`),
 KEY `author_id` (`author_id`),
 CONSTRAINT `phrases_ibfk_1` FOREIGN KEY (`author_id`) REFERENCES `authors` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=55 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

1 个答案:

答案 0 :(得分:0)

我没有测试过,但这应该有效:

UPDATE authors PA 
INNER JOIN (SELECT p.author_id, COUNT( p.author_id ) AS AuthorCount
FROM phrases p
GROUP BY p.author_id) tblA
ON tblA.author_id = PA.id
SET phrases_qt = AuthorCount