以逗号分隔格式输出多个MySql查询

时间:2017-04-08 06:05:33

标签: mysql bash awk

我必须在表上运行多个查询,并以逗号分隔格式获取输出。这是我编写的脚本,但它逐行显示每个Mysql查询的输出。

#!/bin/bash
mysql -uuser -p7pas db -e "select number from hits_log where created_at between '2017-04-07 00:00:00' and '2017-04-08 00:00:00'| while read number; do

mysql -uuser -ppas db -e "select number,count(1) as total_hits from hits_log where number='$number' and time between '2017-04-07 00:00:00' and '2017-04-08 00:00:00' ; select count(1) as xxx from hits_log where number_type='some_value' and old_number='$number' and time between '2017-04-07 00:00:00' and '2017-04-08 00:00:00';"
done

我得到的输出是

number  total_hits

12345   4

xxxx

0

所需的输出是

number total_hits xxxx

12345 4 0

1 个答案:

答案 0 :(得分:0)

你不需要循环。只需加入两个查询。

mysql -e "
    SELECT l1.number, COUNT(*) AS total_hits, IFNULL(l2.xxx, 0) AS xxx
    FROM hits_log AS l1
    LEFT JOIN (
        SELECT old_number, COUNT(*) AS xxx
        FROM hits_log
        WHERE number_type='some_value'
        AND time between '2017-04-07 00:00:00' and '2017-04-08 00:00:00'
        GROUP BY old_number) AS l2
    ON l1.number = l2.old_number
    WHERE time between '2017-04-07 00:00:00' and '2017-04-08 00:00:00'
    GROUP BY l1.number"

如果您确实需要在循环中对单个$number进行查询,您仍然可以加入这两个查询以将它们放在一行中。

mysql -e "
    select number,count(1) as total_hits, xxx 
    from hits_log 
    cross join (
        select count(1) as xxx 
        from hits_log 
        where number_type='some_value' 
        and old_number='$number' 
        and time between '2017-04-07 00:00:00' and '2017-04-08 00:00:00'
    ) as x 
where number='$number' 
and time between '2017-04-07 00:00:00' and '2017-04-08 00:00:00' ;"