我想从不同的表中计算2个表,我选择date
然后我将它分组。
这里我尝试了
SELECT
(SELECT date(date), COUNT(sh_sh) FROM sh_url GROUP BY date(date)) AS URLs,
(SELECT date(date), COUNT(ip) FROM tracking GROUP BY date(date)) AS IP
FROM dual
但我收到错误
1241 - 操作数应包含1列
是否可以在一个命令中执行此操作?
输出应该是这样的
date(url) count(sh_sh) date(ip) count(ip)
--------- ------------ ---------- ----------
2018-04-25 123 2018-04-25 123123
2018-04-26 456 2018-04-26 321
2018-04-27 789 2018-04-27 3125
答案 0 :(得分:2)
我会使用两个子查询的连接来表达你的问题:
SELECT
t1.date,
t1.url_cnt,
COALESCE(t2.ip_cnt, 0) AS ip_cnt
FROM
(
SELECT date, COUNT(*) url_cnt
FROM sh_url
GROUP BY date
) t1
LEFT JOIN
(
SELECT date, COUNT(*) ip_cnt
FROM tracking
GROUP BY date
) t2
ON t1.date = t2.date;
答案 1 :(得分:1)
当您使用子查询作为值时,它只能返回一行和一列。您需要使用JOIN
:
SELECT urls.date, urls.count AS sh_count, ip.count AS ip_count
FROM (SELECT date(date) AS date, COUNT(*) AS count FROM sh_url GROUP BY date(date)) AS urls
JOIN (SELECT date(date) AS date, COUNT(*) AS count FROM tracking GROUP BY date(date)) AS ip
ON urls.date = ip.date