我的SELECT会产生什么吗?

时间:2013-12-16 20:00:19

标签: php mysql sql

我的SELECT有什么问题吗?它应该计算每天不同IP的数量,然后计算总和。这是查询:

SELECT SUM(NumIpsPerDay) AS user_hits
FROM
  (SELECT DATE(tracking.timestamp) AS DayTrackCount,
          COUNT(DISTINCT tracking.ip) AS NumIpsPerDay
   FROM USER,
        tracking
   GROUP BY DATE(tracking.timestamp)
   WHERE tracking.user_id = $user_id
   GROUP BY $user_id LIMIT 1)

我看着它,我想它可能是约会。

我的SELECT是否有任何问题?

3 个答案:

答案 0 :(得分:1)

SELECT SUM(NumIpsPerDay) AS user_hits 
FROM 
(
    SELECT DATE(tracking.timestamp) AS DayTrackCount, 
           COUNT(DISTINCT tracking.ip) AS NumIpsPerDay 
    FROM user, tracking 
    WHERE tracking.user_id = $user_id 
    GROUP BY DATE(tracking.timestamp) 
) x

答案 1 :(得分:0)

试试这个:

SELECT SUM(tab.NumIpsPerDay) AS user_hits
FROM
   (SELECT DATE(tracking.timestamp) AS DayTrackCount,
   COUNT(DISTINCT tracking.ip) AS NumIpsPerDay
   FROM USER, tracking
   WHERE tracking.user_id = $user_id
   GROUP BY DATE(tracking.timestamp)) as tab

为什么要放入子查询日期(tracking.timestamp)?

答案 2 :(得分:0)

嗯,是的。您正在cross joinuser之间执行tracking(笛卡尔积)。但是,您没有使用user表中的任何字段。你可能根本不需要这张桌子。

试试这个:

SELECT SUM(NumIpsPerDay) AS user_hits
FROM (SELECT DATE(tracking.timestamp) AS DayTrackCount,
             COUNT(DISTINCT tracking.ip) AS NumIpsPerDay
      FROM tracking
      WHERE tracking.user_id = $user_id
      GROUP BY DATE(tracking.timestamp
     ) t
GROUP BY $user_id;

另外:

  1. 子查询没有别名
  2. 不需要limit
  3. where
  4. 之后的group by条款