从具有另一个表中的Where的表中选择计数

时间:2015-02-10 12:10:04

标签: php mysql sql join phpmyadmin

我有两张桌子

  • oc2_visits(fields:id_ad)
  • oc2_ads(字段:已发布)

我需要通过对id_ad进行分组来计算访问次数,这是有效的,但我还要求前9个结果的发布时间不超过25天。

这是我目前的查询:

SELECT count(v.id_ad) AS visits,
       v.id_ad,
       a.published
FROM oc2_visits AS v,
     oc2_ads AS a
WHERE DATE(a.published) >= DATE_SUB(NOW(), INTERVAL 25 DAY)
GROUP BY v.id_ad
ORDER BY visits DESC LIMIT 0,9

但是当我尝试在phpmyadmin中输入查询时,它会崩溃。

我做错了什么?

2 个答案:

答案 0 :(得分:1)

大概你问题的根源是两个表之间的笛卡尔积。简单规则:永远不要在from子句中使用逗号。始终使用明确的join语法。

我想你想要的查询看起来像这样:

SELECT count(v.id_ad) AS visits, v.id_ad, a.published
FROM oc2_visits v join
     oc2_ads a
     ON v.id_ad = a.id_ad
WHERE DATE(a.published) >= DATE_SUB(NOW(), INTERVAL 25 DAY)
GROUP BY v.id_ad
ORDER BY visits DESC
LIMIT 0, 9;

答案 1 :(得分:0)

我认为您在与DATE比较时忘记将DATE_SUB(NOW(), INTERVAL 25 DAY)解析为DATE。希望它能运作。

SELECT count(v.id_ad) AS visits,
       v.id_ad,
       a.published
FROM oc2_visits AS v,
     oc2_ads AS a
WHERE DATE(a.published) >= DATE(DATE_SUB(NOW(), INTERVAL 25 DAY))
GROUP BY v.id_ad
ORDER BY visits DESC LIMIT 0,9