![](/img/trans.png)
[英]How do I select distinct values from multiple mysql columns and put them in one PHP array?
[英]Select Distinct Values from different columns MySQL and PHP
我對此有麻煩。 我有一個包含以下各列的mysql表:
該表具有比圖片所示更多的功能,但是我只需要從圖片所示的內容中獲取數據。
這些列包含標記詞,並且經常重復。 我需要獲取一個包含標簽的單個數組,而不要獲取重復的條目,但要獲取所有唯一的條目。
我怎樣才能做到這一點? 為此目的最好的查詢是什么?
另外,如果可能的話,我想計算這個標簽在桌子上出現的次數。
我打算在PHP while()循環上顯示數據,如下所示:
TagA(#個視頻)
TagB(#個視頻)
[...]
您不應該像這樣將標簽存儲在單獨的列中。 相反,它們應該位於一個表格中,每個視頻和每個標記一行。
有了這種結構,您可以使用union all
來做您想做的union all
:
select tag, count(*)
from (select tag1 as tag from t union all
select tag2 as tag from t union all
select tag3 as tag from t union all
select tag4 as tag from t union all
select tag5 as tag from t
) t
group by tag;
如果我正確理解了您的問題,那么任何列中的所有標記詞都將得到同等對待,因此每個標記字段的所有計數的並集應該起作用。
select tag, sum(tagCount) as tagCount from
(select tag1 as tag, count(*) as tagCount from yourTable GROUP BY tag1
UNION
select tag2 as tag, count(*) as tagCount from yourTable GROUP BY tag2
UNION
select tag3 as tag, count(*) as tagCount from yourTable GROUP BY tag3
UNION
select tag4 as tag, count(*) as tagCount from yourTable GROUP BY tag4
UNION
select tag5 as tag, count(*) as tagCount from yourTable GROUP BY tag5)
GROUP BY tag
警告:我前面沒有數據庫連接可立即嘗試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.