将这两个SQL语句合并为一个

时间:2013-05-17 12:23:25

标签: php mysql sql

将这两个SQL语句合并为一个的最佳方法是什么?我尝试使用union,但似乎无处可去。

select id as id from likes where type=1;

select sum(votes) as votes from likes where parent=id;

这是likes表:

id  type  parent  country  votes
 1     1       0       US      0
 2     2       1       US      6 // This +
19     3       1       US      3 // This
 3     3       2       US      3
 7     3       2       US      3
 4    10       3       US      1
 5    10       3       US      1
 6    10       3       US      1
10    10       7       US      1
 9    10       7       US      1
 8    10       7       US      1
20    10      19       US      1
21    10      19       US      1
22    10      19       US      1

这是我想要实现的结果:

id | votes
---------------
1  | 9

4 个答案:

答案 0 :(得分:5)

试试这个:

SELECT 
  l1.id,
  SUM(l2.votes) AS Totalvotes
FROM likes AS l1
INNER JOIN likes AS l2 ON l1.id = l2.parent 
WHERE l1.type = 1 
GROUP BY l1.id;

请在此处查看:

这会给你:

| ID | TOTALVOTES |
-------------------
|  1 |          9 |

答案 1 :(得分:2)

SELECT SUM(votes) AS votes 
FROM likes 
WHERE parent IN (SELECT id FROM likes WHERE type=1)

HTH

答案 2 :(得分:1)

这可以解决你的问题,我相信:

SELECT parent AS id, SUM(votes) AS votes FROM likes WHERE parent IN (SELECT id FROM likes WHERE type = 1) GROUP BY parent;

答案 3 :(得分:0)

你可以试试这个

select id,sum(votes) as votes from likes where type=1 and parent=id;

希望这有帮助