简体   繁体   English

如何获得具有两个对应列的记录,这些列在 SQL 中是多个?

[英]How can I get a record which has two corresponding columns which are multiple in SQL?

For example, I have two tables:例如,我有两个表:

ID | Name
------------
1  | test 1 
2  | test 2 

ID2| ID | Age
--------------
1  | 1  | 18
2  | 1  | 18
3  | 1  | 19
4  | 2  | 18
5  | 2  | 19

I want to have all records that have columns which are multiple in name with age but I don't know how to do that.我想拥有所有列的记录,这些列的名称与年龄有多个,但我不知道该怎么做。

I want an output like this:我想要这样的输出:

Name     | Age
--------------------
test 1   | 18
test 1   | 18

Can anyone help me?谁能帮我?

Try following query:尝试以下查询:

Select t1.*, t2.* 
from table1 t1
join table2 t2
on  t1.id = t2.id
join (select id, age
      from table2
      group by id, age
      having count(*) > 1
     ) t3
on t1.id = t2.id and t2.id = t3.id and t2.age = t3.age

Use exists :使用exists

select t.*
from t
where exists (select 1
              from t t2
              where t2.name = t.name and t2.age = t.age and
                    t2.id <> t.id
             );

With an index on (name, age, id) , this should be the fastest approach.使用(name, age, id)上的索引,这应该是最快的方法。

You can also use an IN on tupples.您还可以IN上使用IN

And a GROUP BY can be combined with a HAVING to only get those that have duplicate (name, age).并且 GROUP BY 可以与 HAVING 结合使用,以只获取那些重复的(姓名、年龄)。

SELECT t1.Name, t2.Age
FROM YourTable2 t2
LEFT JOIN YourTable1 t1 ON t1.ID = t2.ID
WHERE (t2.ID, t2.Age) IN (
      SELECT ID, Age
      FROM YourTable2
      GROUP BY ID, Age
      HAVING COUNT(*) > 1
  );

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

相关问题 如何编写确保两列独立唯一的SQL查询? - How can I write a SQL query which ensures two columns are independently unique? 需要SQL来获取具有两个相应条目的记录 - Need SQL to get a record with two corresponding entries 如何插入多行,每行都有一个数组? - How can i insert multiple rows each of which has an array? 使用PHP Mysql,如何从sql查询中的多个OR条件中满足哪个条件? - Using PHP Mysql how can I get which condition satisfied from multiple OR condition in a sql query? 在SQL或mySQL中,如何在另一列中找到总和最高的键,而该键却出现在两列中? - In SQL or mySQL, how can I find a key which has the highest sum in another column while the key appears in two column? 如何查找表中哪些记录填充了大多数字段? - How can I find which record in a table has most fields populated? 如何在 sql 的两个表上加入多个列 - how can I join multiple columns on two table in sql 如何在SQL的大型数据库中搜索具有2个公共列的表? - How to search for tables which has 2 common columns in a huge database in sql? 如何从多行的两个表中获取数据到单行 - How to get the data from two tables which has multiple rows into a single row 我想获取两列特定列之间的列值 - I want to get the values of the column which are between two specific columns
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM