gpt4 book ai didi

mysql - 从两列中查找出现的次数

转载 作者:行者123 更新时间:2023-11-29 01:57:17 25 4
gpt4 key购买 nike

问题示例:

source | target
apple | dog
dog | cat
door | cat
dog | apple
cat | dog

结果:

apple dog 2
dog cat 2
door cat 1

这是我的问题,例如:

我正在尝试计算源和目标中 appledog 的出现次数。这计数为2,即; apple dogdog cat

同理; dog catcat dog,它们出现了 2 次。

如何使用 mysql 执行此操作?

数据量会很大,这里只是一个简单的例子。

最佳答案

假设 SourceTarget 与一个 ID 相连,我会这样做:

SELECT
FirstValue,
SecondValue,
COUNT(*) As MyCount
FROM
(SELECT
SourceTable.Value FirstValue,
TargetTable.Value SecondValue
FROM
SourceTable
INNER JOIN TargetTable ON SourceTable.IDValue = TargetTable.IDValue
UNION ALL
SELECT
TargetTable.Value FirstValue,
SourceTable.Value SecondValue
FROM
TargetTable
INNER JOIN SourceTable ON TargetTable.IDValue = SourceTable.IDValue)
GROUP BY
FirstValue,
SecondValue

再次阅读问题我不确定这些是否是同一个表中的两列。如果是,则查询可以简化为:

SELECT
FirstValue,
SecondValue,
COUNT(*) As MyCount
FROM
(SELECT
SourceColumn FirstValue,
TargetColumn SecondValue
FROM
MyTable
UNION ALL
SELECT
TargetColumn FirstValue,
SourceColumn SecondValue
FROM
MyTable)
GROUP BY
FirstValue,
SecondValue

关于mysql - 从两列中查找出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25359308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com