首页 > 解决方案 > MYSQL:两个表和预期结果

问题描述

我有两个表,表 1 有唯一的 id 和引用者,表 2 包含表 1 中的一些唯一 id

表格1

uniqueid    | Referrer   
------------------------
abcd1234    | google.com  
27316dsh    | google.com
37283667    | yahoo.com
3728ydhu    | yahoo.com
362ydhhd    | example.com
23819377    | google.com
223hd782    | google.com
2372jdyh    | yahoo.com
qewe7182    | test.com

表 2:

uniqueid    
------------
abcd1234    
27316dsh    
37283667    
3728ydhu    
362ydhhd 

预期结果

Referrer    | Total Referrer | Referrer present in table 2 | Percent
--------------------
google.com  |  4             | 2                           | 50%
yahoo.com   |  3             | 2                           | 66% 
example.com |  1             | 1                           | 100%
test.com    |  1             | 0                           | 0%  

我应该使用什么 SQL 查询来获得预期的结果?

标签: mysql

解决方案


通过to和聚合的LEFT连接:table1table2

select t1.referrer,
       count(*) `Total Referrer`,
       count(t2.uniqueid) `Referrer present in table 2`,
       concat(round(100.0 * count(t2.uniqueid) / count(*)), '%') Percent 
from table1 t1 left join table2 t2
on t2.uniqueid = t1.uniqueid
group by t1.referrer

请参阅演示
结果:

| referrer    | Total Referrer | Referrer present in table 2 | Percent |
| ----------- | -------------- | --------------------------- | ------- |
| example.com | 1              | 1                           | 100%    |
| google.com  | 4              | 2                           | 50%     |
| test.com    | 1              | 0                           | 0%      |
| yahoo.com   | 3              | 2                           | 67%     |

推荐阅读