MySQL SQL 连接:在连接两个表时避免重复条目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4481290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 18:02:43  来源:igfitidea点击:

SQL join: avoid duplicate entries while joining two tables?

sqldatabasemysql

提问by JavaUser

I have two tables, A and B, and I am trying to select rows from A based on a join query. I am getting some records from these tables, but there are some duplicate entries. How should I filter this query to avoid duplicate rows? For now, I'm doing it via Java code by putting these into a HashSet.

我有两个表,A 和 B,我试图根据连接查询从 A 中选择行。我从这些表中获取了一些记录,但有一些重复的条目。我应该如何过滤此查询以避免重复行?现在,我通过 Java 代码将它们放入 HashSet 中。

回答by Jonathan Leffler

The keyword DISTINCT is used to eliminate duplicate rows from a query result:

关键字 DISTINCT 用于从查询结果中消除重复行:

SELECT DISTINCT ...
  FROM A
  JOIN B ON ...

However, you can sometimes (possibly even 'often', but not always) avoid the need for it if the tables are organized correctly and you are joining correctly.

但是,如果表格组织正确并且您正确加入,您有时可以(甚至可能“经常”,但并非总是)避免使用它。

To get more information, you are going to have to ask your question more clearly, with concrete examples.

要获得更多信息,您将不得不通过具体示例更清楚地提出您的问题。

回答by tutorial-computer.com

You must explain table structure but I can understand your question. You may use this query:

您必须解释表结构,但我可以理解您的问题。您可以使用此查询:

select a.atribute1, a.atribute2, b.atribut1, b.atribut2
  from a inner join b
    on a.primarykey = b.foreign_key
 where a.atribute = ""
 group by a.atribute2, b.atribute2

You can use a.atribute = ""for validation.

您可以a.atribute = ""用于验证。

Use group by a.atribute2, b.atribute2if you want the row in one group of this attribute.

group by a.atribute2, b.atribute2如果您想要该属性的一组中的行,请使用。