[英]SQL - COUNT() rows for two tables that are GROUP BY one column in one table
I have two tables.我有两张桌子。 One table is the main table that holds most of the information.
一张表是保存大部分信息的主表。 it has basically two important columns:
它基本上有两个重要的列:
table2_id
type
The second table has only one of those columns and that's id.第二个表只有这些列之一,那就是 id。 However, I have to GROUP BY type since that's what I am needing.
但是,我必须 GROUP BY 类型,因为这就是我所需要的。 But problem occurs because if I GROUP BY id on a joined statement it doesn't give me correct information.
但是会出现问题,因为如果我在连接语句上使用 GROUP BY id,它不会给我正确的信息。 I am needing the other table to get matches AND mismatches from the first table.
我需要另一个表来从第一个表中获取匹配和不匹配。
EXAMPLE table 1:示例表 1:
id type
100 admin
101 user
102 author
103 editor
104 customer
EXAMPLE table 2:示例表 2:
id
100
100
101
101
110
120
100
100
My Results need to look like:我的结果需要看起来像:
type total(COUNT()IN TABLE1) intable2andtable1 difference
admin 200 100 100
user 120 100 20
author 205 200 5
editor 80 70 10
customer 300 100 200
So, some how I need to JOIN and COUNT() the tables.所以,我需要如何 JOIN 和 COUNT() 表。 I was able to get the actual total from the first table.
我能够从第一个表中获得实际总数。 However, if I try to do anything with the ID it makes me add it to the GROUP BY clause and that's messing up my results.
但是,如果我尝试对 ID 执行任何操作,它会使我将其添加到 GROUP BY 子句中,这会弄乱我的结果。
Here is what I have tried:这是我尝试过的:
SELECT type , count(*) as total
FROM table1
GROUP BY type
and that will return:这将返回:
type total(COUNT()IN TABLE1)
admin 200
user 120
author 205
editor 80
customer 300
However, I cannot get the second table involved and showing me the differences between the two.但是,我无法涉及第二个表并向我展示两者之间的差异。
EDIT: Here is a sqlfiddle to make it clearer.编辑:这是一个 sqlfiddle 以使其更清楚。 http://sqlfiddle.com/#!15/08951/2/0
http://sqlfiddle.com/#!15/08951/2/0
It's not entirely clear what the common field between your tables 1 and 2 is, however, assuming it's id
, this query should be what you're after:不完全清楚表 1 和表 2 之间的公共字段是什么,但是,假设它是
id
,则此查询应该是您所追求的:
SELECT type,
COUNT(t1.version_id) as t1_total,
COUNT(t2.version_id) as t2_total,
COUNT(t1.version_id) - COUNT(t2.version_id) as difference
FROM table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.id
GROUP BY type
ORDER BY type ASC
Updated SQL Fiddle here: http://sqlfiddle.com/#!15/08951/20在这里更新了 SQL Fiddle: http ://sqlfiddle.com/#!15/08951/20
From what I understand, you would like to count how many times each type is represented in table2, correct?据我了解,您想计算每种类型在 table2 中表示的次数,对吗? How about this:
这个怎么样:
SELECT table1.type, COUNT(table2.id)
FROM table2 INNER JOIN table1 ON table1.id = table2.id
GROUP BY table2.id`
It should display something like this:它应该显示如下内容:
admin 4
user 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.