Question: Hi I was wondering whether someone would be able to help me with a query. I am trying to select from an EAV type table where the value is not multiple values.

Using the example below I am trying to retrieve rows where tag\_id != 1 and tag\_id != 2. So based on the data I want to return just the row containing contact\_id 3

```
Tags Table:

contact_id     tag_id 
  1             1
  1             2
  2             1
  2             4
  3             4

```

The desire result is to return a single row:

```
contact_id -> 3

```

I have tried the following queries which don't return what I am looking for so are obviously are not correct:

```
select `contact_id` from `contact_tags` where tag_id !=1 and tag_id != 2

select `contact_id` from `contact_tags` where tag_id NOT IN(1,2)

```

Any help on this. Or just a pointer in the right direction would be great.

Answer: 
You can use `NOT EXISTS()` in which the statement inside selects all records where it has tags of `1` or `2`.

```
SELECT  contact_id
FROM    contact_tags a
WHERE   NOT EXISTS
        (
            SELECT  1
            FROM    contact_tags b
            WHERE   tag_id IN (1, 2) AND
                    a.contact_id = b.contact_id
        )
GROUP   BY contact_id

```

* [SQLFiddle Demo](http://sqlfiddle.com/#!2/b2b11/5)

Another alternative is to use `LEFT JOIN`

```
SELECT  a.contact_id
FROM    contact_tags a
        LEFT JOIN contact_tags b
          ON a.contact_id = b.contact_id AND
              b.tag_id IN (1, 2)
WHERE   b.contact_id IS NULL

```

* [SQLFiddle Demo](http://sqlfiddle.com/#!2/b2b11/13)
Stealing from @491243 fiddle here is a modification which returns contacts\_id which lack both tags\_id

<http://sqlfiddle.com/#!2/b2b11/19>