SQL从连接表中获取条目的总和

时间:2013-06-10 20:39:51

标签: mysql sql join

我越陷入mysql,我失去的越多,现在我已经完成了失败。 所以我有一些表格:

MainTable

id|message|name
-----------------
1 |test   |OP
2 |test2  |jim
3 |test3  |ted

表1

id|likes
---------
2 | 1
3 | 0

表2

id|likes
---------
2 | 1

表3

id|likes
---------
1 | 1
2 | 1
3 | 0

我想要做的是为一列中的每个id获取likes的总数(其中a等于1),这样我就可以计算一条消息的总喜欢数(具有各自的id)

直到现在我已经设法加入我的表格,所以我最后得到一个likes列:

SELECT id,Table1.likes,Table2.likes,Table3.likes 
FROM MainTable
LEFT JOIN Table1.id ON MainTable.id = Table1.id LEFT JOIN Table2.id ON MainTable.id = Table2.id LEFT JOIN Table3.id ON MainTable.id = Table3.id

首先,有可能吗?我知道我的代码不是很好,但至少它是一个开始!

谢谢!

3 个答案:

答案 0 :(得分:2)

我猜你正在寻找其中一个...

SELECT
    id
    ,SUM(Table1.likes)
    ,SUM(Table2.likes)
    ,SUM(Table3.likes)
FROM MainTable
LEFT JOIN Table1 ON MainTable.id = Table1.id
LEFT JOIN Table2 ON MainTable.id = Table2.id
LEFT JOIN Table3 ON MainTable.id = Table3.id
GROUP BY MainTable.id

SELECT
    id
    ,SUM(Table1.likes)+SUM(Table2.likes)+SUM(Table3.likes)
FROM MainTable
LEFT JOIN Table1 ON MainTable.id = Table1.id
LEFT JOIN Table2 ON MainTable.id = Table2.id
LEFT JOIN Table3 ON MainTable.id = Table3.id
GROUP BY MainTable.id

答案 1 :(得分:1)

以下是查询,计算MainTable中每行的非零喜欢:

SELECT 
    MainTable.id,
    MainTable.name,
    MainTable.message,
    COUNT(Table1.likes) + COUNT(Table2.likes) 
    + COUNT(Table3.likes) AS n_likes
FROM 
    MainTable
LEFT JOIN 
    Table1 ON MainTable.id = Table1.id
AND
    Table1.likes=1
LEFT JOIN
    Table2 ON MainTable.id = Table2.id
AND
    Table2.likes=1
LEFT JOIN
    Table3
ON
    MainTable.id = Table3.id
AND
    Table3.likes=1
GROUP BY
    MainTable.id;

fiddle

请注意,您的SQL语法有错误:

LEFT JOIN Table1.id

在加入时,您必须编写没有列的表名:

LEFT JOIN Table1

答案 2 :(得分:0)

您可以使用UNION ALL解决此问题。

见下面的测试。

CREATE  TABLE `test`.`items` (
  `id` INT NOT NULL ,
  `message` VARCHAR(45) NULL ,
  `name` VARCHAR(45) NULL ,
  PRIMARY KEY (`id`) );

insert into items values
(1, "Message 1", "OP"),
(1, "Message 2", "jim"),
(1, "Message 3", "ted");


CREATE  TABLE `test`.`table1` (
  `id` INT NOT NULL ,
  `likes` INT(10),
  PRIMARY KEY (`id`) );

CREATE  TABLE `test`.`table2` (
  `id` INT NOT NULL ,
  `likes` INT(10),
  PRIMARY KEY (`id`) );

CREATE  TABLE `test`.`table3` (
  `id` INT NOT NULL ,
  `likes` INT(10),
  PRIMARY KEY (`id`) );

insert into table1 values 
( 2, 1),
( 3, 0);

insert into table2 values 
( 2, 1),
( 3, 0);

insert into table3 values
(1,1),
(2,1),
(3,0);


select source.id, sum(likes)
from (
select id, likes from table1 as t1
UNION ALL
select id, likes from table2 as t2
UNION ALL
select id, likes from table3 as t3
) as source group by id;

输出

1, 1
2, 3
3, 0