无需子查询即可构造mysql select查询

时间:2011-10-28 23:54:31

标签: mysql

我有一张桌子

CREATE TABLE logs(
  id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  ip INT(11) UNSIGNED NOT NULL,
  `date` TIMESTAMP,
  `time` INT(11) UNSIGNED NOT NULL,
  referrer VARCHAR(255) NOT NULL,
  uri VARCHAR(255) NOT NULL,
  PRIMARY KEY (id),
)

我需要通过IP获取以下数据和组:

  • IP
  • 首先用于IP的推荐人(日期是分钟)
  • 上次访问uri for IP
  • 独特的uris数量

是否可以在没有子查询的情况下编写此类查询?

我的子查询解决方案:

SELECT
    `logs`.`ip`,
    (SELECT
        `tmp`.`referrer`
    FROM
        `logs` AS `tmp`
    WHERE
        `tmp`.`ip` = `logs`.`ip`
    ORDER BY `tmp`.`date`
    LIMIT 1) 'referrer',
    (SELECT
        `tmp`.`uri`
    FROM
        `logs` AS `tmp`
    WHERE
        `tmp`.`ip` = `logs`.`ip`
    ORDER BY
        `tmp`.`date` DESC
    LIMIT 1) 'uri',
    COUNT(DISTINCT (`logs`.`uri`)) 'urls'
FROM
    `logs`
GROUP BY
    `logs`.`ip`

1 个答案:

答案 0 :(得分:0)

select
    `logs`.`ip`,
    `tmp`.`referrer`
    `tmp`.`uri`
    count(distinct `logs`.`uri`)) as `urls`
from `logs`
left join `tmp` on `tmp`.`ip`=`logs`.`ip`
group by `logs`.`ip`

然而,这并不允许order by tmp.date部分。如果它是绝对必要的,请在评论中告诉我,我会更新此代码以允许这样做。