将多个mysql查询合并为一个

时间:2010-10-03 06:54:00

标签: mysql

我正在学习Mysql命令和组合多个查询的方法,所以为了获得这个目标,现在我需要结合这些查询:

    list($TotalVisitsToday) = $db->sql_fetchrow($db->sql_query("SELECT  COUNT(DISTINCT ip_address) FROM table_iptracking WHERE `date_time` between '$yesterday' and '$today' "));
    list($TotalVisitsYesterday) = $db->sql_fetchrow($db->sql_query("SELECT  COUNT(DISTINCT ip_address) FROM table_iptracking WHERE `date_time` between '$yesterday_1' and '$yesterday'  "));

    list($TotalPVisitsToday) = $db->sql_fetchrow($db->sql_query("SELECT count(ipid) FROM table_iptracking WHERE `date_time` between '$yesterday' and '$today'"));
    list($TotalPVisitsYesterday) = $db->sql_fetchrow($db->sql_query("SELECT count(ipid) FROM table_iptracking WHERE `date_time` between '$yesterday_1' and '$yesterday'"));

    list($TotalCrawlers) = $db->sql_fetchrow($db->sql_query("SELECT count(ipid) FROM table_iptracking WHERE  hostname LIKE '%crawl%' "));

我不知道如何混合以上几行!

2 个答案:

答案 0 :(得分:0)

您可以将SQL语句组成UNION,例如......

SELECT COUNT(DISTINCT ip_address)
    FROM table_iptracking
    WHERE `date_time` between '$yesterday' and '$today'
UNION
SELECT COUNT(DISTINCT ip_address)
    FROM table_iptracking
    WHERE `date_time` between '$yesterday_1' and '$yesterday'
UNION
SELECT count(ipid)
    FROM table_iptracking
    WHERE `date_time` between '$yesterday' and '$today'
UNION
SELECT count(ipid)
    FROM table_iptracking
    WHERE `date_time` between '$yesterday_1' and '$yesterday'
UNION
SELECT count(ipid)
    FROM table_iptracking
    WHERE hostname LIKE '%crawl%'

但我不能说我会推荐这个。从长远来看,不同行意味着不同事物的结果集可能会很麻烦。

答案 1 :(得分:0)

我不确定你的最终目标,但如果你只想在一个查询中使用它,你可以这样做:

SELECT
(SELECT COUNT(DISTINCT ip_address) FROM table_iptracking WHERE 'date_time' between '$yesterday' and '$today') COUNT1,
(SELECT COUNT(DISTINCT ip_address) FROM table_iptracking WHERE 'date_time' between '$yesterday_1' and     '$yesterday') COUNT2,
(SELECT COUNT(ipid) FROM table_iptracking WHERE 'date_time' between '$yesterday' and '$today') COUNT3,
(SELECT COUNT(ipid) FROM table_iptracking WHERE 'date_time' between '$yesterday_1' and '$yesterday') COUNT4,
(SELECT COUNT(ipid) FROM table_iptracking WHERE  hostname LIKE '%crawl%') COUNT5

(你可以省略MySQL中的FROM caluse)