Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select group of rows that match all items in a list

Assume I have two tables:

cars – list of cars

carname | modelnumber | ... 

passedtest – contains every test that a car passed:

id | carname | testtype | date | ... 1  | carA    | A        | 2000 | 2  | carB    | C        | 2000 | 3  | carC    | D        | 2001 | 4  | carA    | C        | 2002 | 

Now, how can I select a car from the passedtest table that passed all tests (A, B, C, D)?

I tried the IN statement but it also matches cars that pass even one test. I am looking for a statement to match all values in a list across all rows.

like image 358
user1229351 Avatar asked Apr 12 '13 17:04

user1229351


People also ask

Can we use select * with group by?

Cannot use an aggregate or a subquery in an expression used for the group by list of a GROUP BY clause. The original idea was to create the table in beginning of the query, so the (SELECT * FROM #TBL) could be used on the query itself, instead of defining the names on each GROUP BY.

Does everything in select have to be in group by?

Actually, in MySQL you don't have to group by all columns. You can just group by whatever columns you want. The problem is, it will just pull a random value (from the set of available rows in the group) for the fields which aren't in the group by.

Can I group by all in SQL?

Many programmers continue to overlook helpful SQL Server features that have been available for years. Most of these overlooked features can simplify your queries, optimize their performance, and improve your productivity. One such feature is T-SQL's GROUP BY ALL option.

How do I select all rows except one?

You have a few options: SELECT * FROM table WHERE id != 4; SELECT * FROM table WHERE NOT id = 4; SELECT * FROM table WHERE id <> 4; Also, considering perhaps sometime in the future you may want to add/remove id's to this list, perhaps another table listing id's which you don't want selectable would be a good idea.


1 Answers

How about this?

SELECT carname FROM PassedTest GROUP BY carname HAVING COUNT(DISTINCT testtype) = 4 

You can also use it as an inner statement for taking info from the cars table:

SELECT * FROM cars WHERE carname IN (     SELECT carname     FROM PassedTest     GROUP BY carname     HAVING COUNT(DISTINCT testtype) = 4 ) 
like image 88
MarcinJuraszek Avatar answered Oct 07 '22 17:10

MarcinJuraszek