MySQL Query返回“not exists value”

时间:2011-06-23 09:08:20

标签: mysql

我想知道如果我有4个号码可以做到

1,2,3,4

在我的数据库中,数据存在如下

1,2,3,5,6,7

如何查询数据库并在1个查询中返回 4

请告知

2 个答案:

答案 0 :(得分:1)

SELECT id FROM
  ( SELECT 1 AS id UNION
    SELECT 2 UNION
    SELECT 3 UNION
    SELECT 4
  ) AS TBL1
WHERE id NOT IN (SELECT id FROM thetable)

答案 1 :(得分:1)

CREATE TABLE `example` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

INSERT INTO example VALUES (1),(2),(3),(5),(6),(7);

SELECT t2.id FROM example AS t1
RIGHT JOIN (
  SELECT 1 AS id UNION
  SELECT 2 AS id UNION
  SELECT 3 AS id UNION
  SELECT 4 AS id
) AS t2
ON t1.id = t2.id
WHERE t1.id IS NULL;

+----+
| id |
+----+
|  4 |
+----+

或使用临时表:

CREATE TEMPORARY TABLE `tmp` (
  `id` int(11) DEFAULT NULL
) ENGINE=InnoDB;

INSERT INTO tmp VALUES (4);

SELECT t2.id FROM example AS t1
RIGHT JOIN tmp AS t2
ON t1.id = t2.id
WHERE t1.id IS NULL;

要了解发生了什么,请稍微改变一下:

SELECT t1.id, t2.id FROM example AS t1
RIGHT JOIN (
  SELECT 1 AS id UNION
  SELECT 2 AS id UNION
  SELECT 3 AS id UNION
  SELECT 4 AS id
) AS t2
ON t1.id = t2.id;

+------+----+
| id   | id |
+------+----+
|    1 |  1 |
|    2 |  2 |
|    3 |  3 |
| NULL |  4 |
+------+----+