简体   繁体   English

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

[英]Select Distinct Values from different Rows

<?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']."
    ";
}
?>

Hello, I have this code. 您好,我有这段代码。 What i need to do is to get the number of times that a different tag appears in the mentioned rows. 我需要做的是获取不同标签出现在上述行中的次数。 Without repeating Tags. 无需重复标签。 Why is it not working? 为什么不起作用? Can somebody help? 有人可以帮忙吗? I am failing to get it to work. 我无法使其正常工作。

Ty

if you want sum the numbers of all tags you should remove the last group by, to be: 如果要对所有标签的数量求和,则应删除最后一个分组依据,即:

$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)
");

首先,您的查询看起来有些怪异,但由于SUM()函数sum(tagCount as tagCount) ,实际上可能是

select tag, sum(tagCount) as tagCount from

Your specific syntax problems are the typo in the outer select and the lack of alias on the subquery. 您的特定语法问题是外部select中的拼写错误以及子查询上缺少别名。

This is the correct query: 这是正确的查询:

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;

The three key changes: 三个主要更改:

  • Fixing the outer select clause. 修复外部select子句。
  • Using UNION ALL instead of UNION . 使用UNION ALL代替UNION
  • Adding an alias for the subquery. 为子查询添加别名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM