0

我有三个 mysql 数据库表作为

 1) websites
+-----+--------------------+
|  id |website             |
+-----+--------------------+
|   1 | http://abcd.com    |
|   2 | http://xyz.com     |
|   3 | http://pqrs.com    | 
+-----+--------------------+

 2) pages
+-----+---------------------------------------+
|  id |page                                   |
+-----+---------------------------------------+
|   1 | http://abcd.com/index.php             |
|   2 | http://abcd.com/contact.php           |
|   3 | http://xyz.com /index.php             | 
|   4 | http://pqrs.com /index.php            |
+-----+---------------------------------------+

 3) statistics
+-----+-------------------+
|  id |page_id | type     |
+-----+-------------------+
|   1 | 1      | AOL      |
|   2 | 1      | YAHOO    |
|   3 | 2      | AOL      | 
|   4 | 3      | YAHOO    |
|   5 | 3      | YAHOO    |
|   6 | 4      | YAHOO    |
+-----+-------------------+

我希望输出为:

+-------------------+--------------------+
|website            | count_hit_by_AOL   | 
+-------------------+--------------------+
|http://abcd.com    |      2             |
|http://xyz.com     |      0             |
|http://pqrs.com    |      0             |
+-------------------+--------------------+

为了获得这个输出,我正在使用以下 mysql 查询——

SELECT
  COUNT(statistics.id) as count_stats,
  websites.website
FROM websites,
  pages,
  statistics
WHERE pages.page LIKE CONCAT(websites.website,'%')
    AND pages.id = statistics.page_id
    and statistics.type LIKE 'AOL%'
GROUP BY websites.website
ORDER BY count_stats DESC

我得到的输出为

+-------------------+--------------------+
|website            | count_hit_by_AOL   | 
+-------------------+--------------------+
|http://abcd.com    |      2             |
+-------------------+--------------------+

如果我做错了什么,请帮助我,因为我是 MYSQL 的新手。

4

1 回答 1

3

您现有查询的问题是您INNER JOIN在表上使用 an ,因此您只会返回匹配的行。

由于您要返回所有website行,因此您将需要使用LEFT JOIN

SELECT w.website, count(s.id) Total
FROM websites w
LEFT JOIN pages p
  on p.page like CONCAT(w.website,'%')
LEFT JOIN statistics  s
  on p.id = s.page_id
  and s.type like 'AOL%'
group by w.website

请参阅SQL Fiddle with Demo。结果是:

|         WEBSITE | TOTAL |
---------------------------
| http://abcd.com |     2 |
| http://pqrs.com |     0 |
|  http://xyz.com |     0 |

编辑#1,如果你想包括每个网站的总页数,那么你可以使用:

SELECT w.website, 
  count(s.id) TotalStats,
  count(p.page) TotalPages
FROM websites w
LEFT JOIN pages p
  on p.page like  CONCAT (w.website,'%')
LEFT JOIN statistics  s
  on p.id = s.page_id
  and s.type like 'AOL%'
group by w.website

请参阅SQL Fiddle with Demo。这个查询的结果是:

|         WEBSITE | TOTALSTATS | TOTALPAGES |
---------------------------------------------
| http://abcd.com |          2 |          2 |
| http://pqrs.com |          0 |          1 |
|  http://xyz.com |          0 |          1 |
于 2013-03-13T12:11:37.967 回答