Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select item matching Only IN List in sql server

Tags:

How can one select only the items he want in the IN list? for example

select * from pagetags where TagID in (1,2,4) 

Now I want all the pages which has all the above 3 IDs assigned to them (1,2,4), not just any of them but all of them?

Is there a way? any other operator? I have already tried = Any and = All but no luck.

like image 819
Ali Avatar asked Sep 24 '12 11:09

Ali


People also ask

How do I SELECT a list of rows in SQL?

To select rows using selection symbols for character or graphic data, use the LIKE keyword in a WHERE clause, and the underscore and percent sign as selection symbols. You can create multiple row conditions, and use the AND, OR, or IN keywords to connect the conditions.

How do I SELECT all rows except one in SQL?

The SQL EXCEPT operator is used to return all rows in the first SELECT statement that are not returned by the second SELECT statement. Each SELECT statement will define a dataset. The EXCEPT operator will retrieve all records from the first dataset and then remove from the results all records from the second dataset.

Why SELECT * is not recommended?

By using SELECT * , you can return unnecessary data that will just be ignored. But fetching that data is not free of cost. This results in some wasteful IO cycles on the DB end since you will be reading all of that data off the pages. Perhaps you could have read the data from index pages.


1 Answers

The term for this type of problem is relational division. One way below.

SELECT PageID FROM   pagetags WHERE  TagID IN ( 1, 2, 4 ) GROUP  BY PageID HAVING Count(DISTINCT TagID) = 3 
like image 101
Martin Smith Avatar answered Nov 18 '22 17:11

Martin Smith