简体   繁体   中英

How to Count Rows from two Tables with one Command in MySQL

i want to count 2 tables from diferent table, im select the date then i group it.

here what i try

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

but i get error

1241 - Operand should contain 1 column(s)

is that posible to do it in one command?

the output should be like this

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

I would phrase your problems using a join of two subqueries:

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;

When you use a subquery as a value, it can only return one row and one column. You need to use a 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM