简体   繁体   English

MySQL将两行视为一

[英]MySQL count two rows as one

I need to count matches in a database. 我需要计算数据库中的匹配项。

Input: 输入:

id_to    id_from
1        2  
2        1  
1        3
3        1
1        4
5        1

the 5th and 6th row has only one direction so doesn't count 第5和第6行只有一个方向,因此不算

Sample Output: 样本输出:

id_match
1       
2
3

So, for 1 (implicit), 2 and 3 there is a reverse match but for 4 and 5 there aren't. 因此,对于1(隐式),2和3,存在反向匹配,而对于4和5,则没有反向匹配。

---- EDITED ---- ----编辑----

Supposing the table name is "example" and I want to get all matches of id=1 then the SQL query will be: 假设表名是“ example”,并且我想获得所有id = 1的匹配项,那么SQL查询将是:

SELECT count(*) FROM
(SELECT id_to FROM example WHERE id_from = 1) as t1,
(SELECT id_from FROM example WHERE id_to = 1) as t2
WHERE t1.id_to = t2.id_from

but maybe there is a better way to do it 但也许有更好的方法

You could try 你可以试试

SELECT DISTINCT id_from AS matched_id 
FROM   your_table AS data1 
WHERE  EXISTS (SELECT 1 
               FROM   your_table AS data2 
               WHERE  data1.id_from = data2.id_to 
                      AND data1.id_to = data2.id_from) 

I've created a demo here 我在这里创建了一个演示

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

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