MySQL UNION创建奇怪的结果

时间:2019-03-20 02:35:16

标签: mysql sql union

我正在尝试合并两个表的数据,以便按状态获取总线索数。但是,由于某种原因,它要从table_1获得所有线索,并将其置于TX(Texas)下。两个查询在分开时可以正常工作,但与联合结合时不能正常工作。

TX  197 (This is the combined total of all leads in table_1)
CA  102 (This is the total for table_2. Does not include table_1)
TX  48  (This is the total for table_2. Does not include table_1)
FL  37  (This is the total for table_2. Does not include table_1)
MO  35  ...
NY  25  ...
etc. etc.

这是我的查询...

SELECT state, count(*) AS cnt FROM `table_1` WHERE submission_date > CURDATE() - INTERVAL 2 YEAR AND unk IS NULL 
UNION ALL
SELECT state, count(*) AS cnt FROM `table_2` WHERE submission_date > CURDATE() - INTERVAL 2 YEAR AND unk IS NULL 
GROUP BY state
ORDER BY cnt DESC

2 个答案:

答案 0 :(得分:1)

我认为您需要一些括号,因此group by在联合之后执行,并将计数移出

let colour = message.member.displayHexColor;
let color = colour.slice(1).trim().split(/ +/g);
message.channel.send({embed: {
    color: `${color}`,
    description: "A very simple Embed!"
}});

答案 1 :(得分:0)

GROUP BY仅适用于 second 子查询。那不是你想要的。

在大多数数据库中,您的查询将生成错误。我想你想要

SELECT state, SUM(cnt) as cnt
FROM ((SELECT state, count(*) AS cnt
       FROM `table_1`
       WHERE submission_date > CURDATE() - INTERVAL 2 YEAR AND unk IS NULL
      ) UNION ALL
      (SELECT state, count(*) AS cnt
       FROM `table_2`
       WHERE submission_date > CURDATE() - INTERVAL 2 YEAR AND unk IS NULL 
       GROUP BY state
      )
     ) s
GROUP BY state
ORDER BY SUM(cnt) DESC;

在每个子查询中进行GROUP BY是可选的。但是,GROUP BY的性能增长比线性增长快。因此,即使有外部聚合,两个较小的GROUP BY通常也比一个较大的<div class="row"> <div class="slider slider-single"> <div><h3>1</h3></div> <div><h3>2</h3></div> <div><h3>3</h3></div> <div><h3>4</h3></div> <div><h3>5</h3></div> <div><h3>6</h3></div> <div><h3>7</h3></div> <div><h3>8</h3></div> <div><h3>9</h3></div> <div><h3>10</h3></div> <div><h3>11</h3></div> <div><h3>12</h3></div> <div><h3>13</h3></div> <div><h3>14</h3></div> <div><h3>15</h3></div> <div><h3>16</h3></div> </div> <div class="ellipses"><span>...</span></div> <div class="slider slider-nav"> <div><h3><span>1</span></h3></div> <div><h3><span>2</span></h3></div> <div><h3><span>3</span></h3></div> <div><h3><span>4</span></h3></div> <div><h3><span>5</span></h3></div> <div><h3><span>6</span></h3></div> <div><h3><span>7</span></h3></div> <div><h3><span>8</span></h3></div> <div><h3><span>9</span></h3></div> <div><h3><span>10</span></h3></div> <div><h3><span>11</span></h3></div> <div><h3><span>12</span></h3></div> <div><h3><span>13</span></h3></div> <div><h3><span>14</span></h3></div> <div><h3><span>15</span></h3></div> <div><h3><span>16</span></h3></div> </div> <div class="ellipses2"><span>...16</span></div> </div> 要快。