0

我在mysql中潜得越深,我失去的越多,现在我完全迷路了。所以我有一些表:

主表

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

我想要做的是获取likes一列中每个 id 的总数(其中 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

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

谢谢!

4

3 回答 3

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
于 2013-06-10T20:51:42.850 回答
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;

小提琴

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

LEFT JOIN Table1.id

加入时必须写表名,不包括列:

LEFT JOIN Table1
于 2013-06-10T21:06:30.563 回答
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
于 2013-06-10T20:48:19.417 回答