开发者

what is the difference beteween two queries

I personally feel i am giving same condition t开发者_StackOverflow社区o both the queries then why do they produce different results. While i think they should produce same results. I just dont understand this aberrant nature. Please explain me this.

SELECT 
    MIN(EventID ) 
FROM 
    [3rdi_Events] 
WHERE
    EventID IN (
        SELECT DISTINCT
            EventId
        FROM 
            [3rdi_EventDates] 
        WHERE 
            EventDate Between '2/9/2011' AND '3/11/2012'
            )
GROUP BY 
    EventTypeId

and

SELECT 
    EventId 
FROM 
    [3rdi_Events] AS E 
WHERE
    E.EventID IN (
        SELECT 
            min(EventId) 
        FROM 
            [3rdi_Events] 
        GROUP BY
            EventTypeId
    )
    AND 
    E.EventID IN (
        SELECT DISTINCT 
            EventId
        FROM 
            [3rdi_EventDates] 
        WHERE 
            EventDate Between'2/9/2011' AND '3/11/2012'
    )


In the second query in the part:

WHERE
E.EventID IN (
    SELECT 
        min(EventId) 
    FROM 
        [3rdi_Events] 
    GROUP BY
        EventTypeId
)

you do not have condition for eventdate, so you search the minimum element from the table, and also with the other part:

   AND 
E.EventID IN (
    SELECT DISTINCT 
        EventId
    FROM 
        [3rdi_EventDates] 
    WHERE 
        EventDate Between'2/9/2011' AND '3/11/2012'
)

to be in that date range. So if a minimum isn't in that range it would not display it. However, the first query returns minimum element from that date range


Consider this:

EventId          Date     EventType
1                1/1/11   1
2                3/3/11   1

The first query includes events whose date is within 2/9/11 and 3/11/12, that is event no. 2.

The second query only includes events with the min EventId for given type (no. 1) (first subselect), and whose date is between 2/9/11 and 3/11/12 (second subselect). No row matches this combination.


In the first query you are selecting the minimum EventId thats dates fall within '2/9/2011' and '3/11/2012'

In the second query you are selecting the EventId where the the EventID is the minumum in the table and where the dates fall in between the '2/9/2011' and '3/11/2012'

If in the second query if the minimum EventId in the table does not fall within those dates no value should be returned.

I think.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜