php - 包含计数的 4 路 SQL 查询

标签 php mysql sql

我有 4 张 table :

  1. ad (id, ...)
  2. website (id, title, URL, ...)
  3. space (id, website_id, ...)
  4. ad_space_counter (id, ad_id, website_id, space_id, impression_counter, click_counter)

一个网站可能分配有 2 或 3 个空间。

现在我希望实现的是进行一次选择并获得以下结果:

  1. ad_id
  2. website_id
  3. URL (from website table)
  4. title (from website table)
  5. impression_counter (but the TOTAL of all spaces assigned to that specific website_id)
  6. click_counter (but the TOTAL of all spaces assigned to that specific website_id)

因此,如果我们有 ad_id =1 和 website_id = 1,但有 3 个空格且 website_id = 1,那么 ad_space_counter 将生成 3 个条目,每个条目都有自己的特定展示次数和点击计数器。此 SELECT 必须获取所有这些的总和并将其显示在一个结果中。

谢谢。

最佳答案

请尝试使用以下内容,请注意“ad_id”列未包含在列列表中。因此下面的查询可以被视为网站的统计数据。

select 
       a.website_id,
       website.url,
       website.title,
       sum(a.impression_counter) as impression_counter,
       sum(a.click_counter) as click_counter
from ad_space_counter a, 
     ad,
     website
     space
where ad.id = a.ad_id
   and website.id = a.website_id
   and space.id = a.space_id
group by 
       a.website_id,
       website.url,
       website.title

关于php - 包含计数的 4 路 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19907718/

相关文章:

mysql - mysql列名必须以字母开头吗?

mysql - 如何只选择姓氏相同的人?数据库

sql - 将缺失的信息添加到表中? (考虑随机开始和结束月份)

php - 使用错误的表别名生成查询的原则

mysql - 获取我的标 checkout 现在 mysql 查询中的计数

mysql - 我如何: ORDER BY COUNT(column1) from the result of: SELECT DISTINCT column1,栏2

php mysql查询首字母!=[a-z]

php - 搜索数组中的值不起作用

php - 特定页面 wordpress 顶部导航的自定义 css

javascript - 从 Ajax 将数组数组传递给 Controller