连接两个查询不同的表

时间:2019-04-30 07:10:17

标签: php mysql sql

我想查找在我的推荐表中显示最高的前4个赞助商,并在我的推荐表中汇总每个赞助商的奖金,并回显该赞助商,出现的次数以及从中获得的奖金总和推荐表。

这是我的两个表的数据库模式

$bonuses = "CREATE TABLE IF NOT EXISTS bonuses (
    userid int (11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    sponsor VARCHAR (16) NOT NULL,
    username VARCHAR (20) NOT NULL,
    bonus int (6) NOT NULL,
    bonusid VARCHAR (5) NOT NULL,
    time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    status int (1) NOT NULL DEFAULT '0'
   )ENGINE=InnoDB DEFAULT CHARSET= latin1";

$query = mysqli_query($conn, $bonuses);

$referrals = "CREATE TABLE IF NOT EXISTS referrals (
    userid int (11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    sponsor VARCHAR (16) NOT NULL,
    username VARCHAR (20) NOT NULL,
    phoneNumber VARCHAR (11) NOT NULL,
    email VARCHAR (50) NOT NULL,
    reg_Date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    totalbonus int (7) NOT NULL DEFAULT '0',
    status int (1) NOT NULL DEFAULT '1',
    UNIQUE KEY (username)
   )ENGINE=InnoDB DEFAULT CHARSET= latin1";

$query = mysqli_query($conn, $referrals);

<?php
$query=mysqli_query($conn, "SELECT sponsor, COUNT(sponsor) AS numref FROM referrals  where not sponsor='admin' GROUP BY sponsor ORDER BY numref DESC LIMIT 4");
            echo '<div style="font-size:20px; font-weight:bold; color: #fff; background-color:#800040; padding: 5px; border-radius: 10px;
            box-shadow:2px 2px 2px 2px #aaa; margin-bottom:2px;">WPM Award Statistics(Top 4)</div>';
            echo '<div class="table-responsive">';
            echo "<table class='table table-bordered table-hover table-striped'>";
            echo '<thead style="color:#800040;"><tr><th>Sponsor</th><th>Num of Referrals</th></tr></thead>';
        while ($result = mysqli_fetch_array($query)) {
            $sponsor=$result['sponsor'];
            $numref=$result['numref'];
            echo '<tbody><tr><td>', "$sponsor", '</td><td>', "$numref", '</td></tr></tbody>';

        }
            echo '</table></div>';
?>

这是我已经得到的赞助商和推荐表的编号

我想回显第三列,其中包含status = 3的每个赞助商的奖金总和

1 个答案:

答案 0 :(得分:0)

SELECT ref.sponsor, COUNT(ref.sponsor) AS numref, sum(bns.bonus) as bonuses 
FROM referrals ref
LEFT JOIN bonuses bns ON bns.sponsor = ref.sponsor
WHERE NOT ref.sponsor='admin' AND bns.status = 3
GROUP BY ref.sponsor 
ORDER BY numref DESC 
LIMIT 4

OR

SELECT ref.sponsor, COUNT(ref.sponsor) AS numref, 
(SELECT sum(bonus) FROM bonuses WHERE sponsor = ref.sponsor AND status = 3) AS bonuses
FROM referrals ref
WHERE NOT ref.sponsor='admin'
GROUP BY ref.sponsor 
ORDER BY numref DESC 
LIMIT 4