从同一个表加入复杂的mysql查询

时间:2016-03-05 07:09:16

标签: mysql

这有效:

    SELECT * 
FROM ( SELECT 
SUM(count) AS valid,
SUBSTRING_INDEX(REPLACE(REPLACE(REPLACE(ref_url,'http://',''),'https://',''),'www.',''),'/',1) AS sDomain 
FROM ref_records
WHERE user_id = 9507
GROUP BY sDomain 
ORDER BY 1 DESC) 
as A

INNER JOIN

( SELECT 
SUM(invalid) AS invalid,
SUBSTRING_INDEX(REPLACE(REPLACE(REPLACE(ref_url,'http://',''),'https://',''),'www.',''),'/',1) AS sDomain
FROM ref_records
WHERE user_id = 9507
GROUP BY sDomain 
ORDER BY 1 DESC) 
as B


on A.sDomain=B.sDomain

但是它会输出下表:

valid | sDomain | invalid | sDomain

现在我希望将相同的结果合并如下:

sDomain | valid | invalid

有什么想法吗?感谢。

1 个答案:

答案 0 :(得分:2)

您可以在选择中选择唯一项目和其他项目的总和,然后使用group by statement。

检查以下声明:

select A.sDomain ,sum(valid) as valid, sum(invalid)
from A INNER JOIN B ON A.sDomain=B.sDomain
group By A.sDomain