用于检查Mysql中表中某些键是否存在的SQL查询

时间:2011-02-04 16:35:35

标签: mysql exists

我在应用中输入了一些静态文本keys。我的应用程序还有一个可以使用的keys表。我想编写一个查询,检查表中是否存在所有静态keys。如果缺少某些内容,我想知道它们是keys

这是一个示例表...

+----------+
|  column  |
+----------+
|   val1   |
+----------+
|   val2   |
+----------+
|   val3   |
+----------+

在这个例子中,我想检查表中不存在哪个静态值val1,val3,val4,val5。如何编写查询来实现此目的?

1 个答案:

答案 0 :(得分:3)

select key_name from keys_tab 
    where key_name not in 
    (select t2.key_name from keys_tab t2, other_tab t1 
       where t2.key_name = t1.key_name);

select key_name from keys_tab 
    where key_name not in 
    (select t2.key_name from keys_tab t2, other_tab t1 
       where t2.key_id = t1.key_id);

可以在子查询中使用distinct

select key_name from keys_tab 
    where key_name not in 
    (select distinct t2.key_name from keys_tab t2, other_tab t1 
       where t2.key_id = t1.key_id);

示例

mysql> select * from test1;
+----------+----------------------+---------------------+-------+
| col1     | col2                 | mdate               | myrow |
+----------+----------------------+---------------------+-------+
| col1     | 1/29/2011 9:59:47 AM | 2011-02-01 11:40:07 |  NULL |
| val2     | NULL                 | 2011-02-04 22:09:11 |  NULL |
| val4     | NULL                 | 2011-02-04 22:09:15 |  NULL |
+----------+----------------------+---------------------+-------+
3 rows in set (0.00 sec)

mysql> select * from test2;
+------+------+
| col1 | col2 |
+------+------+
| val1 | val2 |
| val2 | val3 |
| val4 | val3 |
+------+------+
3 rows in set (0.00 sec)

mysql> select * from test2 where col1 not in (select t2.col1 from test2 t2, test1 t1 where t2.col1 = t1.col1);
+------+------+
| col1 | col2 |
+------+------+
| val1 | val2 |
+------+------+
1 row in set (0.00 sec)

mysql>

你需要的就是这个

CREATE TEMPORARY TABLE key_list(key_name varchar(100));
insert into key_list values ('val1'),('val2'),('val3'),('val4'),('val5');
select key_name from key_list where key_name not in (select distinct col1 from test1);

然后使用上面提到的临时表。我相信一定有更好的方法。

  

创建表时可以使用TEMPORARY关键字。 TEMPORARY表仅对当前连接可见,并在关闭连接时自动删除。

http://dev.mysql.com/doc/refman/5.1/en/create-table.html

相关问题