简体   繁体   English

如何在连接两个表后仅选择唯一的行

[英]How to select only the unique rows after joining two table

i have two tables: 我有两张桌子:

table 'A'
| id | name  |
| 1  | Larry |
| 2  | Maria |
| 3  | Ponyo |
| 4  | Panda |


table 'B'
| m_id | items |
| 1    |  7    |
| 2    |  9    |

I just want to display the records from table 'A' that are NOT on table 'B'. 我只想显示表'A'中不在表'B'上的记录。 So that would be 那就是

| 3  | Ponyo |
| 4  | Panda |

only. 只要。

An anti-join pattern is usually the most efficient approach, although there are several ways to get the same result. 反连接模式通常是最有效的方法,尽管有几种方法可以获得相同的结果。

SELECT a.id
     , a.name
  FROM table_a a
  LEFT
  JOIN table_b b
    ON b.id = a.id
 WHERE b.id IS NULL

Let's unpack that a bit. 让我们解开一下。

The LEFT [OUTER] JOIN operation gets us all rows from a , along with matching rows from b . LEFT [OUTER] JOIN操作从a获取所有行,以及b中的匹配行。 The "trick" is to filter out all the rows that had a match; “技巧”是过滤掉所有匹配的行; to do that, we use a predicate in the WHERE clause, that checks for a NULL value from b that we know won't be NULL if a match was found. 为此,我们在WHERE子句中使用谓词,该谓词检查b中的NULL值,如果找到匹配,我们知道该值不为NULL。

In this case, if we found a match, we know b.id is not null, since b.id = a.id wouldn't return TRUE if b.id was NULL. 在这种情况下,如果我们找到匹配,我们知道b.id不为null,因为如果b.id为NULL,则b.id = a.id不会返回TRUE。

The anti-join won't create any "duplicate" rows from a (like a regular join can do). 反连接不会从a创建任何“重复”行(就像常规连接一样)。 If you need to eliminate "duplicates" that already exist in a, adding a GROUP BY clause or adding the DISTINCT keyword before the select list is the way to go. 如果您需要消除a中已存在的“重复”,添加GROUP BY子句或在选择列表之前添加DISTINCT关键字是要走的路。


There are other approaches, like using a NOT EXISTS predicate with a correlated subquery, or a NOT IN with a subquery, but those forms are usually not as efficient. 还有其他方法,例如使用带有相关子查询的NOT EXISTS谓词,或带子查询的NOT IN ,但这些表单通常效率不高。


FOLLOWUP 跟进

Actual performance of the queries is going to depend on several factors; 查询的实际性能取决于几个因素; having suitable indexes available is probably the biggest factor. 拥有合适的指数可能是最大的因素。 The nullability of columns involved in predicates plays a role in the execution plan, as does cardinality, distribution of values, etc., MySQL version, and configuration of the server (eg innodb pool size) 谓词中涉及的列的可为空性在执行计划中起作用,基数,值的分布等,MySQL版本和服务器的配置(例如,innodb池大小)也是如此。

As a test case: 作为测试用例:

SHOW VARIABLES LIKE 'version'
-- Variable_name  Value                        
-- -------------  -----------------------------
-- version        5.5.35-0ubuntu0.12.04.2-log  

CREATE TABLE `table_a` (
  `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `name_` VARCHAR(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB;

CREATE TABLE `table_b` (
  `a_id` INT(10) UNSIGNED NOT NULL DEFAULT '0',
  `item` INT(10) UNSIGNED NOT NULL DEFAULT '0',
  PRIMARY KEY (`a_id`,`item`)
) ENGINE=INNODB;

-- table_a  1,000,000 rows, id values   1 through 1000000
-- table_b    990,000 rows, a_id values 1 through 1000000 (less a_id MOD 100 = 0)

left-join-where 左加入,其中

-- EXPLAIN
SELECT /*! SQL_NO_CACHE */ a.id
     , a.name_
  FROM table_a a
  LEFT
  JOIN table_b b
    ON b.a_id = a.id
 WHERE b.a_id IS NULL

not-in 未在

-- EXPLAIN 
SELECT /*! SQL_NO_CACHE */ a.id
     , a.name_
  FROM table_a a
 WHERE a.id NOT IN (SELECT b.a_id FROM table_b b)

not-exists 不存在

-- EXPLAIN 
SELECT /*! SQL_NO_CACHE */ a.id
     , a.name_
  FROM table_a a
 WHERE NOT EXISTS 
       (SELECT 1
          FROM table_b b
         WHERE b.a_id = a.id)

Performance results (in seconds): 效果结果(以秒为单位):

                  run 2  run 3  run 4  run 5  avg
                  -----  -----  -----  -----  -----
left-join-where   0.227  0.227  0.227  0.227  0.227 
not-in            0.233  0.233  0.234  0.233  0.233
not-exists        1.031  1.029  1.032  1.031  1.031

EXPLAIN output for the three queries: 三个查询的EXPLAIN输出:

left-join-where  
id  select_type        table type           possible_ key     key_len ref       rows Extra                                 
--  -----------        ----- -------------- --------- ------- ------- ------ ------- ------------------------------------
 1  SIMPLE             a     ALL                                             1000392                                       
 1  SIMPLE             b     ref            PRIMARY   PRIMARY 4       a.id         1 Using where; Using index; Not exists

not-in
id  select_type        table type           possible_ key     key_len ref       rows Extra        
--  ------------------ ----- -------------- --------- ------- ------- ------ ------- ------------------------------------
 1  PRIMARY            a     ALL                                             1000392 Using where  
 2  DEPENDENT SUBQUERY b     index_subquery PRIMARY   PRIMARY 4       func         1 Using index 

not-exists
id  select_type        table type           possible_ key     key_len ref       rows Extra        
--  ------------------ ----- ------         --------- ------- ------- ------ ------- ------------------------------------
 1  PRIMARY            a     ALL                                             1000392 Using where  
 2  DEPENDENT SUBQUERY b     ref            PRIMARY   PRIMARY 4       a.id         1 Using index

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

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