GomoX
GomoX

Reputation: 917

How can I avoid both aggregate functions and subqueries when GROUP BY'ing a primary key?

Say I have two tables:

I want to grab all the objects that had an event happen during a date range. I want to get at most a single row for every object, but many events on the same object can happen in the date range. The following query gives me the ids I want:

SELECT object.id
FROM object
JOIN ON object.id = object_event.object_id
WHERE object_event.date < ...
GROUP BY object.id

This is OK, but what if I want the other fields in the object table as well? I can't have aggregate functions on them (name is a string), but because id is object's primary key, there is a functional dependency saying there is no ambiguity in something like:

SELECT object.*
<rest of query same as above>

MySQL allows this, but MS SQL does not. I know I can solve this with a subquery, but I would like to avoid that.

Upvotes: 0

Views: 273

Answers (1)

Code Magician
Code Magician

Reputation: 23982

You don't really want to do a join here, you're instead looking for set inclusion.

Something like this would work better and will be more efficient than implementing a distinct sort or a group by.

SELECT O.* 
FROM object O
WHERE EXISTS (SELECT * FROM object_event E WHERE date BETWEEN @myDate1 AND @mydate2 AND E.object_id = O.id)

Upvotes: 4

Related Questions