如何判断是否与其他表没有关联

时间:2011-06-13 00:04:04

标签: mysql

我有3个MySQL表:tags,place_tags,event_tags

标记:

---------------------
|  tag_id  |  name  |
---------------------
|    1     |  cat   |
---------------------
|    2     |  dog   |
---------------------
|    3     |  fish  |
---------------------

place_tags:

-------------------------
|  place_id  |  tag_id  |
-------------------------
|      1     |     1    |
-------------------------
|      2     |     2    |
-------------------------
|      3     |     1    |
-------------------------

event_tags:

-------------------------
|  event_id  |  tag_id  |
-------------------------
|      1     |     1    |
-------------------------
|      2     |     2    |
-------------------------
|      3     |     1    |
-------------------------

我正在尝试编写一个查询,查看tags表中的所有标记,并查找哪些标记与其他表中的任何一个都没有关联。在此示例中,您可以看到tag_id 3未在任何其他表中使用,因此我想选择它并输出它。

2 个答案:

答案 0 :(得分:2)

高效,使用索引,单一SELECTJOIN的查询可以是:

   SELECT tags.*
     FROM tags
LEFT JOIN place_tags ON place_tags.tag_id = tags.tag_id
LEFT JOIN event_tags ON event_tags.tag_id = tags.tag_id
    WHERE place_tags.tag_id IS NULL AND
          event_tags.tag_id IS NULL

这会加入您正在查看的表格,只选择其中任何一个都没有对应关系的标记。

答案 1 :(得分:1)

select * from tag
where not exists (select * from place_tags where tag_id = tag.tag_id)
and not exists (select * from event_tags where tag_id = tag.tag_id)

或更高效,但也许更难阅读:

select * from tag
where tag_id not in (
    select tag_id from place_tags where tag_id is not null
    union
    select tag_id from event_tags where tag_id is not null)

注意:需要where tag_id is not null,因为如果其中一行的tag_idnull,则in将始终为false