Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 将这两条SQL语句合并为一条_Php_Mysql_Sql - Fatal编程技术网

Php 将这两条SQL语句合并为一条

Php 将这两条SQL语句合并为一条,php,mysql,sql,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

将这两条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
试试这个:

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 |
你可以试试这个

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

希望这有助于解决您的问题,我相信:

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

他们做不同的事情。你想完成什么?我已经用表格更新了问题和我想完成的。你的解决方案给了我每一行。是的。谢谢这很有效。一件小事,在我开始之前,如果我需要指定另一个where条件,我应该在哪里做?像这样:
其中l1.type=1和l1.country='us'
?@Norman-是的,像这样
其中l1.type=1和l1.country='us'
:对不起,我没有把这个问题想得足够仔细。更新后的答案应该有效,尽管我现在无法真正测试它。现在有效。只是一点测试。它不起作用,因为您将在同一行中操作,即您实际上正在查找父级和id相等的行。您需要在同一个表上使用子查询或联接—不能回避它。
SELECT parent AS id, SUM(votes) AS votes FROM likes WHERE parent IN (SELECT id FROM likes WHERE type = 1) GROUP BY parent;