6

Think about a table like this

ID     Value    
100    1    
100    3    
101    1    
101    4    
102    2    
102    5    
103    2    
103    4    
104    1    
104    3    
105    2    
105    5

The problem is, if I give values 2 and 5 I should get 102 and 105 which both 102 and 105 are having values 2 and 5 at the same time or if I give values 1 and 3 I should get 100 and 104.

How can I do this with only one sql command? I need a query as light as possible.

and using UNION, INTERSECTION or NESTED SQLs, which one is faster, slower, heavier e.t.c?

Thanks in advance Ergec

2
  • Thank you guys, I started to test queries to find the fastest and the lightest one. It seems that Rufinus's query is the fastest. 20,000 records, 1006 results Jhonny average 0.0045 seconds David average 0.0020 seconds Rufinus average 0.0010 seconds (I'd never think doing in this way :)) I am open to new suggestions Commented Aug 10, 2009 at 14:48
  • Even tough Rufinus' answer is the fastest I'd select David's answer. Its fast enough and flexible so I can group values with ANDs and ORs Commented Aug 11, 2009 at 15:02

3 Answers 3

7

Try something like this:

SELECT id
  FROM test
WHERE 
   value in (2,5)
GROUP by id
HAVING count(*) = 2

If you want to test it, simple table for it (with no indexes!):

CREATE TABLE IF NOT EXISTS test (
  id int(4) NOT NULL,
  `value` int(4) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO test (id, value) VALUES
(100, 1),
(100, 3),
(101, 1),
(101, 4),
(102, 2),
(102, 5),
(103, 2),
(103, 4),
(104, 1),
(104, 3),
(105, 2),
(105, 5);

I had a very similar question a few days ago. see MySQL - Find rows matching all rows from joined table

Sign up to request clarification or add additional context in comments.

Comments

1

There's lots of solutions. Addition to the Jhonny's solution, you can use a join

SELECT DISTINCT t1.id
FROM table t1, table t2
WHERE t1.id = t2.id
  AND t1.value = 2
  AND t2.value = 5

OR use Intersect

SELECT id FROM table WHERE value = 2

INTERSECT

SELECT id FROM table WHERE value = 5

Comments

0

This would be my way to achieve it:

SELECT DISTINCT id
FROM table 
WHERE 
id IN (SELECT id FROM table WHERE value = 2)
AND 
id IN (SELECT id FROM table WHERE value = 5)

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.