我如何使用不同表的记录数创建视图
How I create a view with the record count of different tables
我需要创建一个 视图,其中包含来自 3 个不同 table 但具有相同列的记录数。
也就是这些查询
SELECT COUNT (*) AS count_a from table1 ta
SELECT COUNT (*) AS count_b from table2 tb
SELECT COUNT (*) AS count_c from table3 tc
在视图中引入,join
可以是一个解决方案,但我认为这需要大量工作,同样在每个 table 中都是不同的计数,当使用 join 时它会丢弃一些,如果 table 中有 100、200、15。不,我知道加入是否可以解决这个问题。
我想使用 GROUP_CONCAT
但复习了一下似乎不是一个解决方案,无论如何。简单来说,我想要在一个视图中计算不同 table 的数量,以便显示
想要的结果
count_a
count_b
count_c
100
200
15
提前问候和感谢
PS:现在我不太记得 JOIN 是如何工作的
尝试这样的查询:
SELECT
(SELECT count(*) FROM table1) AS count_a,
(SELECT count(*) FROM table2) AS count_b,
(SELECT count(*) FROM table3) AS count_c;
如果只想显示这3个计数的结果,不进行任何表间连接。我建议使用这样的脚本:
create view desired_result
as select * from (
(SELECT COUNT(*) AS count_a from table1) t1,
(SELECT COUNT(*) AS count_b from table2) t2,
(SELECT COUNT(*) AS count_c from table3) t3);
你可以试试这个fiddle link
如果你喜欢没有JOIN
:
SELECT
(SELECT count(*) as count_a FROM table1) AS count_a,
(SELECT count(*) as count_b FROM table2) AS count_b,
(SELECT count(*) as count_c FROM table3) AS count_c;
如果你喜欢 JOIN
:
SELECT ta.count_a, tb.count_b, tc.count_c FROM
(
SELECT COUNT (*) AS count_a, 1 AS rn from table1) ta
JOIN (
SELECT COUNT (*) AS count_b, 1 AS rn from table2) tb
ON ta.rn = tb.rn
JOIN (
SELECT COUNT (*) AS count_c, 1 AS rn from table3) tc
ON ta.rn = tc.rn
我需要创建一个 视图,其中包含来自 3 个不同 table 但具有相同列的记录数。
也就是这些查询
SELECT COUNT (*) AS count_a from table1 ta
SELECT COUNT (*) AS count_b from table2 tb
SELECT COUNT (*) AS count_c from table3 tc
在视图中引入,join
可以是一个解决方案,但我认为这需要大量工作,同样在每个 table 中都是不同的计数,当使用 join 时它会丢弃一些,如果 table 中有 100、200、15。不,我知道加入是否可以解决这个问题。
我想使用 GROUP_CONCAT
但复习了一下似乎不是一个解决方案,无论如何。简单来说,我想要在一个视图中计算不同 table 的数量,以便显示
想要的结果
count_a | count_b | count_c |
---|---|---|
100 | 200 | 15 |
提前问候和感谢
PS:现在我不太记得 JOIN 是如何工作的
尝试这样的查询:
SELECT
(SELECT count(*) FROM table1) AS count_a,
(SELECT count(*) FROM table2) AS count_b,
(SELECT count(*) FROM table3) AS count_c;
如果只想显示这3个计数的结果,不进行任何表间连接。我建议使用这样的脚本:
create view desired_result
as select * from (
(SELECT COUNT(*) AS count_a from table1) t1,
(SELECT COUNT(*) AS count_b from table2) t2,
(SELECT COUNT(*) AS count_c from table3) t3);
你可以试试这个fiddle link
如果你喜欢没有JOIN
:
SELECT
(SELECT count(*) as count_a FROM table1) AS count_a,
(SELECT count(*) as count_b FROM table2) AS count_b,
(SELECT count(*) as count_c FROM table3) AS count_c;
如果你喜欢 JOIN
:
SELECT ta.count_a, tb.count_b, tc.count_c FROM
(
SELECT COUNT (*) AS count_a, 1 AS rn from table1) ta
JOIN (
SELECT COUNT (*) AS count_b, 1 AS rn from table2) tb
ON ta.rn = tb.rn
JOIN (
SELECT COUNT (*) AS count_c, 1 AS rn from table3) tc
ON ta.rn = tc.rn