0

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 advise

2
  • 1
    Erm, SELECT 4 FROM [TableName]?! Commented Jun 23, 2011 at 9:10
  • 1
    This might be what you need: stackoverflow.com/questions/2886797/… Commented Jun 23, 2011 at 9:20

2 Answers 2

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 |
+----+

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 |
+------+----+
Sign up to request clarification or add additional context in comments.

3 Comments

Did I need to create the table every time I want to use this query?
The example table? No, that's just to give you an idea of how it works. The example table is just a replacement for your real table.
Thank you again Mike for your nice explaination
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.