mysql选择不同的值(并计算值的数量)

时间:2017-12-14 08:48:42

标签: mysql multiple-tables

我卡住了MySQL查询。我有6个类似列的表。在您提出要求之前,需要单独更新并删除;连同数据的数量。

因此,要从多个表中获取总和,我使用SELECT SUM(x)FROM(SELECT COUNT(value)as x etc)

要获得一个唯一ID,我使用DISTINCT(value)。现在我需要将它们组合成一个2列查询,因此我有一个唯一的值和计数。

我的数据看起来像这样,例如表格1表格(乘以6):

    till_no  | fruit  | vegetables
    123      | apple  |  null
    123      | apple  | carrot
    125      | apple  | pear
    124      | apple  | null

我想要的是123 | 2,124 | 1,125 | 1

    SELECT DISTINCT(y), SUM(a) FROM (
      (SELECT till_no as y, (SELECT COUNT(till_no)  FROM Shop1) as a FROM Shop1 c)
      UNION (SELECT till_no as y, (SELECT COUNT(_till_no)  FROM Shop2) 
           as a FROM Shop2 c)
       ) multipleTables

2 个答案:

答案 0 :(得分:0)

无需使用DISTINCT。 GROUP BY子句将代表您接受。您可以尝试以下查询 -

SELECT CONCAT(y, COUNT(y)) 
FROM (SELECT till_no as y FROM Shop1
      UNION
      SELECT till_no as y FROM Shop2
      UNION
      SELECT till_no as y FROM Shop3
      UNION
      SELECT till_no as y FROM Shop4
      UNION
      SELECT till_no as y FROM Shop5
      UNION
      SELECT till_no as y FROM Shop6) multiple tables
GROUP BY y

答案 1 :(得分:0)

Ankit让我走上了正确的道路。

解决方案是:

     SELECT z, SUM(y) 
     FROM (SELECT ea as z, COUNT(ea) as y FROM table1 GROUP BY ea
     UNION
     SELECT ea as z, COUNT(ea) as y FROM table2 GROUP BY ea
     UNION
     SELECT ea as z, COUNT(ea) as y FROM table3 GROUP BY ea
     UNION
     SELECT ea as z, COUNT(ea) as y FROM table4 GROUP BY ea
     UNION
     SELECT ea as z, COUNT(ea) as y FROM table5 GROUP BY ea
     UNION
     SELECT ea as z, COUNT(ea) as y FROM table6 GROUP BY ea) 
     multipletables
     GROUP BY y

解决方案的诀窍是将其分解为小步......逻辑上1 + 1肯定击败47 + 126