从不同的行中选择不同的值

时间:2016-01-18 15:53:25

标签: php mysql

<?php
include("includes/dbconnect.php");
$getTagsQuery = mysql_query("
select tag, sum(tagCount as tagCount) from
(select tag1 as tag, count(*) as tagCount from videos GROUP BY tag1
UNION
select tag2 as tag, count(*) as tagCount from videos GROUP BY tag2
UNION
select tag3 as tag, count(*) as tagCount from videos GROUP BY tag3
UNION
select tag4 as tag, count(*) as tagCount from videos GROUP BY tag4
UNION
select tag5 as tag, count(*) as tagCount from videos GROUP BY tag5)
GROUP BY tag
");
while ($row = mysql_fetch_array($getTagsQuery)){
echo "
    ".$row['tagCount']."
    ";
}
?>

你好,我有这个代码。 我需要做的是获得在提到的行中出现不同标记的次数。 不重复标签。 为什么不起作用? 有人可以帮忙吗? 我没能让它发挥作用。

3 个答案:

答案 0 :(得分:0)

如果您想要将最后一个组删除的所有标签的数量加起来为:

$getTagsQuery = mysql_query("
select tag, sum(tagCount as tagCount) from
(select tag1 as tag, count(*) as tagCount from videos GROUP BY tag1
UNION
select tag2 as tag, count(*) as tagCount from videos GROUP BY tag2
UNION
select tag3 as tag, count(*) as tagCount from videos GROUP BY tag3
UNION
select tag4 as tag, count(*) as tagCount from videos GROUP BY tag4
UNION
select tag5 as tag, count(*) as tagCount from videos GROUP BY tag5)
");

答案 1 :(得分:0)

首先,您的查询看起来有点奇怪,但由于SUM()函数sum(tagCount as tagCount)实际应该是

,您可能会收到错误
select tag, sum(tagCount) as tagCount from

答案 2 :(得分:0)

您的特定语法问题是外部select中的拼写错误以及子查询中缺少别名。

这是正确的查询:

select tag, sum(tagCount) as tagCount
from ((select tag1 as tag, count(*) as tagCount from videos GROUP BY tag1
      ) UNION ALL
      (select tag2 as tag, count(*) as tagCount from videos GROUP BY tag2
      ) UNION ALL
      (select tag3 as tag, count(*) as tagCount from videos GROUP BY tag3
      ) UNION ALL
      (select tag4 as tag, count(*) as tagCount from videos GROUP BY tag4
      ) UNION ALL
      (select tag5 as tag, count(*) as tagCount from videos GROUP BY tag5
      )
     ) t
GROUP BY tag;

三个关键变化:

  • 修复外部select子句。
  • 使用UNION ALL代替UNION
  • 为子查询添加别名。