mysql - 如何不重复派生表的子查询

时间:2014-03-12 17:57:07

标签: mysql sql subquery derived

我想知道列的值显示在结果中的次数,并将其包含在每行的结果列中。如何在不重复派生表的子查询两次的情况下实现此目的?如果我在COUNT子查询中用“t”替换(derivedtable),它表示该表不存在。

SELECT
col1,
col2,
col3,
(SELECT COUNT(*) FROM (derivedtable) WHERE t.col1=col1)
FROM (derivedtable) AS t

2 个答案:

答案 0 :(得分:0)

你能使用group by吗?

SELECT col1, col2, col3, COUNT(*)
FROM (derivedtable) AS t
GROUP BY col1;

这将返回col2col3的任意值。您可以使用group_concat()获取完整列表:

SELECT col1, group_concat(col2) as col2s, group_concat(col3) as col3s, COUNT(*)
FROM (derivedtable) AS t
GROUP BY col1;

编辑:

如果你真的想在不重复派生表的情况下这样做,你可以使用变量:

SELECT col1, col2, col3,
       @col1cnta := if(@col1a = col1, @col1cnta, col1cnt) as col1cnt,
       @col1a := col
FROM (SELECT col1, col2, col3,
             @col1cnt := if(@col1 = col1, 0, @col1cnt) + COUNT(*) as col1cnt,
             @col1 := col1
      FROM (derivedtable) t cross join
           (select @col1 := '', @col1cnt := 0) const
      GROUP BY col1
     ) t cross join
     (select @col1a := '', @col1cnta := 0) const
ORDER BY col1, col1cnt desc;

这里的想法是为三列的每个组合做子量。然后,按col1对结果进行排序,但计数顺序相反,并将最大值复制到给定col1的所有行。

答案 1 :(得分:0)

Solution :

SELECT col1, col2, col3,
       @col1cnta := if(@col1a = col1, @col1cnta, col1cnt) as col1cntfinal,
       @col1a := col1
FROM (SELECT col1, col2, col3,
             @col1cnt := if(@col1 = col1, @col1cnt+1, 1) as col1cnt,
             @col1 := col1
      FROM (derivedtable) t cross join
           (select @col1 := '', @col1cnt := 0) const
      ORDER BY col1
     ) t2 cross join
          (select @col1a := '', @col1cnta := 0) const
ORDER BY col1, col1cnt desc;