我有两个MySQL表赞助和事件。我想显示一个赞助商列表,按照他们赞助的活动类别排序,但只在每个活动下展示一次赞助。样本连接表:
SPONSORSHIPS
sponsorhipid | sponsorid | eventid | date |
-------------|-----------|---------|------------|
1 | 3 | 20 | 06/01/2013 |
2 | 2 | 20 | 06/02/2013 |
3 | 3 | 20 | 06/03/2013 |
4 | 2 | 21 | 06/04/2013 |
EVENTS
eventid | name | premium |
--------|-----------|------------|
20 | Lunch | 0 |
21 | Dinner | 1 |
JOIN的结果是:
sponsorhipid | sponsorid | eventid | date | name | premium |
-------------|-----------|---------|------------|---------| ---------|
1 | 3 | 20 | 06/01/2013 | Lunch | 0 |
2 | 2 | 20 | 06/02/2013 | Lunch | 0 |
4 | 2 | 21 | 06/04/2013 | Dinner | 1 |
我尝试了DISTINCT
和GROUP BY
但是这些事件已经崩溃了,所以如果赞助商#2赞助两个不同的活动,他们仍然只会展示一次。我怎样才能做到这一点?这是我最后一次SQL查询:
SELECT DISTINCT (sponsorships.sponsorshipid), sponsorships.*, events.*
FROM events
INNER JOIN sponsorships
ON events.eventid = sponsorships.eventid
非常感谢任何指针!
答案 0 :(得分:1)
您需要使用这样的嵌套子查询:
SELECT s.sponsorhipid, s.sponsorid, s.eventid, s.date
,e.name, e.premium
FROM EVENTS e
JOIN
(
SELECT s1.* FROM SPONSORSHIPS s1
JOIN
(
SELECT sponsorid, MIN(Date) As minDate
FROM SPONSORSHIPS
GROUP BY eventid,sponsorid
) s2
ON s1.sponsorid = s2.sponsorid
AND s1.date = s2.minDate
) s
ON e.eventid = s.eventid;
输出:
| SPONSORHIPID | SPONSORID | EVENTID | DATE | NAME | PREMIUM |
|--------------|-----------|---------|------------|--------|---------|
| 1 | 3 | 20 | 06/01/2013 | Lunch | 0 |
| 2 | 2 | 20 | 06/02/2013 | Lunch | 0 |
| 4 | 2 | 21 | 06/04/2013 | Dinner | 1 |