Mysql 对两列进行查询,就好像它们是一列一样
有两列包含相同类型的数据:Mysql 对两列进行查询,就好像它们是一列一样,mysql,sql,database,Mysql,Sql,Database,有两列包含相同类型的数据: col_a col_b ... Bob Tim .. John Frank . Bob John John Tim Bob Bob Frank John 现在我要做的查询是这样的:Bob,3,John,2,…: SELECT col_a, count(*) AS total FROM table1 GROUP BY col_a 但是我不想在a列上运行它,我想同时在a列和b列上运行它,鲍勃,4,约翰,4 谢谢你的帮助 编辑: 谢谢大
col_a col_b ...
Bob Tim ..
John Frank .
Bob John
John Tim
Bob Bob
Frank John
现在我要做的查询是这样的:Bob,3,John,2,…:
SELECT col_a, count(*) AS total FROM table1 GROUP BY col_a
但是我不想在a列上运行它,我想同时在a列和b列上运行它,鲍勃,4,约翰,4
谢谢你的帮助
编辑:
谢谢大家,你太棒了
再次感谢基于您的Bob Bob专栏,我认为您需要分组子查询:
select Name, count(*) as Total
from (
select col_a as Name from MyTable
union all
select col_b from MyTable
) a
group by Name
select idx, sum(count)
from (
select col_a as idx, count(*) as count
from table
union all
select col_b as idx, count(*) as count
where col_a <> col_b -- avoid dups
) as counts
group by idx
或:
快速回答!Z作为别名吗?>让我头疼@N8-Z是任意的。可以使用任何您喜欢的别名,只要您使用别名。
select idx, sum(count)
from (
select col_a as idx, count(*) as count
from table
union all
select col_b as idx, count(*) as count
where col_a <> col_b -- avoid dups
) as counts
group by idx
select idx, count(*)
from (
select col_a as idx
from table
union all
select col_b as idx
where col_a <> col_b -- avoid dups
) as counts
group by idx