Mysql union所有选择问题

时间:2017-01-10 21:49:07

标签: mysql union-all

我想知道我在哪里出错了。我使用不同的Where语句从同一个表中加入多个select语句,其中一个选择也是连接。我试图使用联盟,但我似乎错过了一些东西,我无法弄清楚它是什么。任何帮助都会很棒。以下是我的代码:

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>';
}

2 个答案:

答案 0 :(得分:0)

对于union,所有集合应该具有相同的列数。在您的情况下,第一个查询也有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)

答案 1 :(得分:0)

所以我可能会在这种情况下帮助别人,这就是我所寻找的结果:

pip3 install --upgrade pip