我有一张桌子
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获取以下数据和组:
是否可以在没有子查询的情况下编写此类查询?
我的子查询解决方案:
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`
答案 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
部分。如果它是绝对必要的,请在评论中告诉我,我会更新此代码以允许这样做。