我试图从两个不同的表中获取计数并将它们组合在一起。我遇到的问题是我要么在30分钟内获得很长的查询时间+或者它只是没有显示我想要的方式。
我将这部分的代码用于半工作并使用工会快速运行。 (这很可能是错误的,但我尝试加入的所有尝试都使得运行时间非常长)
select `model`, count(*) as "Test1"
from `table1`
group by `model`
union
select `model`, count(*) as "Test2"
from `table2`
group by `model`
这将显示一个巨大的滚动列表上的计数,其中第一个计数显示然后另一个。同时只显示" Test1"文本," Test2"不会显示。
我想拥有它,以便它们彼此相邻显示,这样我就可以看到我与其他表模型相比有多少模型。
任何帮助将不胜感激,抱歉第一次发布在这里的任何混乱
编辑:尽我所能给出我用联合代码看到的一小部分样本
Model |Test1
Suzuki| 2
Honda | 19
Suzuki| 5
Honda | 26
所以会出现类似的东西,前两个结果来自第一个select语句,另外两个来自第二个select语句。
我正在寻找的结果更像是这样。
Model | Test1 Model | Test2
Suzuki| 2 Suzuki| 5
Honda | 19 Honda | 26
答案 0 :(得分:1)
这在mySQL中很难做到,因为它不像其他RDBMS一样支持FULL OUTER JOIN。
我认为你可以得到你想要的东西:
select * from
(
select t1.model, count(*) as "Test1"
from table1 as t1
group by model
) as tt1
left outer join
(
select t2.model, count(*) as "Test2"
from table2 as t2
group by model
) as tt2
ON tt1.model = tt2.model
UNION
select * from
(
select t3.model, count(*) as "Test1"
from table1 as t3
group by model
) as tt3
right outer join
(
select t4.model, count(*) as "Test2"
from table2 as t4
group by model
) as tt4
ON tt3.model = tt4.model
这里有一个小提琴:http://sqlfiddle.com/#!9/5a155/1
然而,大多数人会选择不同的输出格式,这不需要那么多体操。
编辑由于对其中一条评论的回答。
如果您知道table2不包含不在table1中的任何模型,则SQL变得更简单:
select model,
(select count(*) as "Test1"
from table1 as t1
where t0.model = t1.model
) as "Test1",
(select count(*) as "Test1"
from table2 as t2
where t0.model = t2.model
) as "Test2"
from table1 as t0
group by model
;