MySQL-从两个表中获取数据

时间:2018-12-01 09:33:16

标签: mysql

我有两个表webadstats和webstatsclick,我想从这两个表中进行以下查询。

$sql2 = "SELECT
    count(*) as 'impressions',
    unix_timestamp(date(from_unixtime(A.time))) as 'timestamp',
    COUNT(B.click) as 'clickss'
FROM `webadstats` as A
LEFT JOIN `webstatsclick` as B
ON A.pubadhash = B.pubadhash
WHERE A.pubadhash='$pubadhash'
GROUP BY date(from_unixtime(A.time))";

$result2 = mysqli_query($conn, $sql2);
if (mysqli_num_rows($result2)>0) {
    while($row = mysqli_fetch_assoc($result2)) {
        $impressions[] = $row['impressions'];
        $clicksall[] = $row['clickss'];
        $timestamp[] = $row['timestamp'];
    }

     for($i=0; $i<count($clicksall); $i++){
    $str .= $timestamp[$i] . '||' . $impressions[$i] . '||' . $clicksall[$i]  ."\n";
    }

}

echo $str;

但是问题是,此查询正在为印象数和点击数两个变量生成相同的值,而印象数变量的值是正确的。

1542434400||1270||1270
1542520800||1800||1800
1542607200||1745||1745
1542693600||1805||1805
1542780000||1615||1615
1542866400||1740||1740
1542952800||1740||1740
1543039200||1830||1830
1543125600||1830||1830
1543212000||1615||1615
1543298400||1880||1880
1543384800||2125||2125
1543471200||1530||1530
1543557600||1370||1370
1543644000||120||120

我俩的数据库结构都是 webadstats数据库

webadstats db

webstatsclick数据库

webstatsclick db

请帮助我哪里错了。

1 个答案:

答案 0 :(得分:0)

让我们回到两种查询方法。问题是,我们一直在尝试在pubadhash上使用JOIN,但也尝试在pubadhash上使用WHERE,因此值会相乘。

$sql2 = "SELECT
    count(*) as 'impressions',
    unix_timestamp(date(from_unixtime(time))) as 'timestamp'
FROM `webadstats`
WHERE pubadhash='$pubadhash'
GROUP BY date(from_unixtime(time))";

$sql3 = "SELECT
    count(*) as 'clickss',
    unix_timestamp(date(from_unixtime(time))) as 'timestamp'
FROM `webstatsclick`
WHERE pubadhash='$pubadhash'
GROUP BY date(from_unixtime(time))";

$result2 = mysqli_query($conn, $sql2);
if (mysqli_num_rows($result2)>0) {
    while($row = mysqli_fetch_assoc($result2)) {
        $arr[$row['timestamp']]['impressions'] = $row['impressions'];
        $arr[$row['timestamp']]['timestamp'] = $row['timestamp'];
        $arr[$row['timestamp']]['clickss'] = 0;
    }

    $result3 = mysqli_query($conn, $sql3);
    if (mysqli_num_rows($result3)>0) {
        while($row = mysqli_fetch_assoc($result3)) {
            $arr[$row['timestamp']]['clickss'] = $row['clickss'];
        }
    }

    foreach($arr as $clicks){
        $str .= $clicks['timestamp'] . '||' . $clicks['impressions'] . '||' . $clicks['clickss']  ."\n";
    }

}

echo $str;