2017-01-10 107 views
0

我想弄清楚我在哪裏出錯了。我正在使用不同的Where語句從同一個表中加入多個select語句,其中一個選擇也是一個連接。我試圖使用工會,但我似乎失去了一些東西,我不知道它是什麼。任何幫助都會很棒。下面是我的代碼:Mysql union所有選擇問題

SET @LASTQTR:=IF((QUARTER(CURDATE())-1) = 0, 4, QUARTER(CURDATE())-1); 
SET @YR:=IF(@LASTQTR = 4, YEAR(NOW())-1, YEAR(NOW())); 

(SELECT COUNT(r.id) AS total, CONCAT(m1.first_name,' ', m1.last_name) AS fromName FROM Referrals AS r JOIN Members AS m1 ON m1.id=r.from_id WHERE QUARTER(rdate) = @LASTQTR AND YEAR(rdate) = @YR GROUP BY r.from_id) 
    UNION ALL 
    (SELECT COUNT(id) AS external FROM Referrals WHERE QUARTER(rdate) = @LASTQTR AND YEAR(rdate) = @YR AND rtype=1 GROUP BY from_id) 
    UNION ALL 
    (SELECT COUNT(id) AS internal FROM Referrals WHERE QUARTER(rdate) = @LASTQTR AND YEAR(rdate) = @YR AND rtype=2 GROUP BY from_id) 
    ORDER BY total DESC LIMIT 10; 

我要尋找從該查詢使用導致while循環,像這樣的最終結果是:

while ($re = $q8->fetch(PDO::FETCH_ASSOC)) { 
    echo'<tr> 
    <td style="width:40%;">'.$re['fromName'].'</td> 
    <td class="text-right">'.$re['external'].'</td> 
    <td class="text-right">'.$re['internal'].'</td> 
    <td class="text-right">'.$re['total'].'</td> 
    </tr>'; 
} 

回答

0

工會的所有集應該有相同的不列。在你的情況下,第一個查詢也有fromName。要麼刪除或把佔位符其他查詢以及

SET @LASTQTR:=IF((QUARTER(CURDATE())-1) = 0, 4, QUARTER(CURDATE())-1); 
SET @YR:=IF(@LASTQTR = 4, YEAR(NOW())-1, YEAR(NOW())); 

(SELECT COUNT(r.id) AS total, CONCAT(m1.first_name,' ', m1.last_name) AS fromName FROM Referrals AS r JOIN Members AS m1 ON m1.id=r.from_id WHERE QUARTER(rdate) = @LASTQTR AND YEAR(rdate) = @YR GROUP BY r.from_id) 
    UNION ALL 
    (SELECT COUNT(id) AS external,'' FROM Referrals WHERE QUARTER(rdate) = @LASTQTR AND YEAR(rdate) = @YR AND rtype=1 GROUP BY from_id) 
    UNION ALL 
    (SELECT COUNT(id) AS internal,'' FROM Referrals WHERE QUARTER(rdate) = @LASTQTR AND YEAR(rdate) = @YR AND rtype=2 GROUP BY from_id) 
    ORDER BY total DESC LIMIT 10; 

根據您的評論(還沒有執行此)

(SELECT COUNT(r.id) AS total, CONCAT(m1.first_name,' ', m1.last_name) AS fromName, 
(SELECT COUNT(id) FROM Referrals WHERE QUARTER(rdate) = @LASTQTR AND YEAR(rdate) = @YR AND rtype=1 GROUP BY from_id) AS external, 
(SELECT COUNT(id) FROM Referrals WHERE QUARTER(rdate) = @LASTQTR AND YEAR(rdate) = @YR AND rtype=2 GROUP BY from_id) AS internal 
    FROM Referrals AS r JOIN Members AS m1 ON m1.id=r.from_id WHERE QUARTER(rdate) = @LASTQTR AND YEAR(rdate) = @YR GROUP BY r.from_id) 
+0

使用上面的這個問題是當循環遍歷結果時,它將每個sel ect語句作爲while循環中的新行。我認爲使用Union將會返回每行所有三個選擇的結果。 –

+0

請參閱我對原始問題的編輯 –

0

所以我有可能會幫助其他人在這種情況下,這是什麼給了我正在尋找的結果:

SELECT COUNT(r.id) AS total, CONCAT(m1.first_name,' ', m1.last_name) AS fromName, 
(SELECT COUNT(id) FROM Referrals WHERE rtype=1 AND from_id=r.from_id GROUP BY fromName) AS external, 
(SELECT COUNT(id) FROM Referrals WHERE rtype=2 AND from_id=r.from_id GROUP BY fromName) AS internal 
FROM Referrals AS r JOIN Members AS m1 ON m1.id=r.from_id WHERE QUARTER(rdate) = @LASTQTR AND YEAR(rdate) = @YR GROUP BY fromName ORDER BY total DESC LIMIT 10