简体   繁体   中英

Mysql - Get data from two tables

I have two tables webadstats and webstatsclick and i want to make below query from these two tables.

$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;

But the problem is that this query is generating same values for both the variables impressions and clickss out of which value of impressions variable is correct.

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

My both the DB structure is webadstats db

webadstats db

webstatsclick db

webstatsclick db

Kindly help me where i am wrong.

Let's go back to the two query approach. The problem is, we've been trying to use JOIN on pubadhash but also WHERE with pubadhash, so the values get multiplied.

$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;

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