计算MyISAM MySQL表中的不同表

时间:2010-11-04 16:11:40

标签: mysql

我编写了下面的代码作为示例从不同的MyISAM MySQL表中获取,我不能使用UNION来计数,只有第一个值变为正确而另一个为空

实际上哪个是第一个,那是因为我听说我的桌子是MyISAM。

(SELECT COUNT(*) AS userCount from table_users)
UNION 
(SELECT COUNT(*) AS totalposts from table_stories)

那么解决方案是什么?

1 个答案:

答案 0 :(得分:1)

如果您希望两个结果都在同一行,则可以使用子查询。测试用例:

CREATE TABLE table_users (id int) ENGINE=MYISAM;
CREATE TABLE table_stories (id int) ENGINE=MYISAM;

INSERT INTO table_users VALUES (1), (2), (3);
INSERT INTO table_stories VALUES (1), (2), (3), (4), (5), (6);

SELECT (SELECT COUNT(*) from table_users) userCount,
       (SELECT COUNT(*) from table_stories) totalposts;
+-----------+------------+
| userCount | totalposts |
+-----------+------------+
|         3 |          6 |
+-----------+------------+
1 row in set (0.00 sec)

另一方面,如果您希望将结果放在单独的行中,那么您使用的查询也应该起作用:

(SELECT COUNT(*) AS count_value from table_users)
UNION
(SELECT COUNT(*) from table_stories);
+-------------+
| count_value |
+-------------+
|           3 |
|           6 |
+-------------+
2 rows in set (0.02 sec)