mysql列计数与值计数(redux)不匹配:是的。还是吗?

时间:2012-10-12 20:32:38

标签: mysql

MySQL是否让我感到悲伤,因为insert语句中的嵌套SELECT使用COUNT(*)函数而不是选择实际的列?那么,解决方法是什么?

以下是故事:

mysql> explain test;
+----------+----------------------+------+-----+---------+-------+
| Field    | Type                 | Null | Key | Default | Extra |
+----------+----------------------+------+-----+---------+-------+
| language | varchar(50)          | YES  |     | NULL    |       |
| count    | smallint(5) unsigned | YES  |     | NULL    |       |
+----------+----------------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> SELECT languages.name, COUNT(*) AS `total` FROM languages JOIN events ON languages.id     = events.language_id GROUP BY name HAVING total > 250 ORDER BY total DESC;
+-----------+-------+
| name      | total |
+-----------+-------+
| Spanish   | 60079 |
| Foochow   |  2838 |
| Mandarin  |  2396 |
| Russian   |  1675 |
| Arabic    |  1410 |
| Cantonese |  1358 |
| Korean    |   736 |
| French    |   531 |
| Punjabi   |   426 |
| Urdu      |   408 |
| Hebrew    |   276 |
| Pashto    |   255 |
+-----------+-------+
12 rows in set (0.00 sec)

mysql> INSERT INTO test (`language`,`count`) VALUES ((SELECT languages.`name`, COUNT(*) AS `total` FROM languages JOIN events ON languages.id = events.language_id GROUP BY name HAVING total > 250 ORDER BY total DESC));
ERROR 1136 (21S01): Column count doesn't match value count at row 1

感谢。

2 个答案:

答案 0 :(得分:1)

MySQL不支持这种多列返回子查询,因此您看到的错误消息是因为VALUES子句只包含一个子查询,这是perforce(在某种意义上)只有一个列。

要解决此问题,您可以跳过VALUES语法,只需编写:

INSERT
  INTO test (`language`,`count`)
SELECT languages.`name`, COUNT(*) AS `total`
  FROM languages
  JOIN events
    ON languages.id = events.language_id
 GROUP
    BY name
HAVING total > 250
 ORDER
    BY total DESC
;

(见§13.2.5.1 "INSERT ... SELECT Syntax" in the MySQL 5.6 Reference Manual。)

答案 1 :(得分:0)

  

INSERT INTO test(`language`,`count`)

应该是

INSERT INTO test (language,count)