简体   繁体   English

帮助编写SQL查询

[英]help writing sql query

I have a database that looks like: 我有一个数据库,看起来像:

contacts 往来

id | name
1  | bob
2  | jack
3  | jill

contactsGroupLink contactsGroupLink

cId| gId
1  | 1
2  | 3
2  | 3
2  | 5
3  | 4

So basically, 所以基本上

a contact is linked to a group by an entry in the contactsGroupLink table. 联系人通过contactsGroupLink表中的条目链接到组。

A contact may be in multiple groups, but a contact may only be on a group once. 一个联系人可以在多个组中,但是一个联系人只能在一个组中一次。

The query I want to write is 我要写的查询是

select `name` 
  from contacts 
 where contact.id not in (select contactId 
                           from contactsGroupLink 
                          where groupId = 5);

Which works. 哪个有效。 It returns bob and jill . 它返回bobjill

however its not very optimized as it has a dependent sub-query. 但是,由于它有一个依赖的子查询,因此优化程度不是很高。 can anyone help optimize it? 谁能帮助优化它?

Because both columns are unlikely to be NULL, in MySQL ( only ) the best option is to use the LEFT JOIN/IS NULL : 因为两个列都不太可能为NULL,所以在MySQL( )中,最好的选择是使用LEFT JOIN / IS NULL

   SELECT c.name
     FROM CONTACTS c
LEFT JOIN CONTACTSGROUPLINK cgl ON cgl.contactid = c.id
                               AND cgl.groupid = 5
    WHERE cgl.contactid IS NULL

If the columns were nullable , NOT EXISTS is a better choice: 如果列是可空的 ,则NOT EXISTS是更好的选择:

   SELECT c.name
     FROM CONTACTS c
    WHERE NOT EXISTS (SELECT NULL
                        FROM CONTACTSGROUPLINK cgl
                       WHERE cgl.contactid = c.id
                         AND cgl.groupid = 5)

The two columns in the CONTACTSGROUPLINK table should be the primary key, which will automatically index the columns (as of ~5.0+?). CONTACTSGROUPLINK表中的两列应该是主键,它将自动索引这些列(从〜5.0开始?)。 Otherwise, make sure the columns are indexed. 否则,请确保对列进行索引。

... ...

where not exists (
  select 1 from contactsGroupLink cgl
  where cgl.contactid = contact.id and cgl.groupid = 5
)

This should efficiently use the index by contactsGroupLink(contactid, groupid) you already have. 这应该通过您已经拥有的contactsGroupLink(contactid,groupid)有效地使用索引。

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

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