I want to know is it possible to do if I have 4 number as below
1,2,3,4
In my data base have data exists as below
1,2,3,5,6,7
How can I query database and return 4 in 1 query
Please advis开发者_StackOverflow社区e
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 |
+----+
Or use a temporary table:
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;
To see what's happening, switch things around a bit:
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 |
+------+----+
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)
精彩评论