2

I have a martial arts website where I have users in one table and the belts they have earned in another. Here are some example tables / data to help describe my problem:

Users table :

+---------------------+
| Users               |
+---------------------+
| userid | name       |
+---------------------+
|    1   | Fred Smith |
+---------------------+

Belts table :

+------------------------------------------+
| id | userid | belt_colour | awarded_date |
+------------------------------------------+
| 1  |    1   |   blue      |  2007-01-01  |
+------------------------------------------+
| 2  |    1   |   purple    |  2008-01-01  |
+------------------------------------------+
| 2  |    1   |   brown     |  2009-01-01  |
+------------------------------------------+

My problem is this: When you click brown, to view all brown belts I want you to see Fred. I DO NOT want Fred to appear in lists of blue and purple belts (which is what is happening at the moment).

I am struggling to come up with a query that goes something like this:

show me all users where belt=$belt but only if they do not have an entry for a higher belt.

Another example: I am purple but I show up in blue list because details of my blue belt are in the belts table too :-(

Any assistance greatly appreciated!

4

3 回答 3

3

假设更高的腰带意味着更高的奖励日期,一种选择是获取MAX每个用户的奖励日期并重新加入腰带表:

SELECT u.userId, u.name
FROM Users u
    JOIN (
        SELECT userId, MAX(awarded_date) max_awarded_date
        FROM Belts
        GROUP BY userId
   ) maxb ON u.userId = maxb.userId
   JOIN Belts b ON b.userId = maxb.userId 
       AND b.awarded_date = maxb.max_awarded_date
WHERE b.belt_colour = 'brown'
于 2013-05-27T16:00:15.897 回答
1

按_awarded_date_降序排序。并将结果限制为 1。

由于每条腰带都是一个接一个地授予的,因此最近的就是您要展示的腰带。因此,您的查询将是这样的:

 select * from Users u, Belts b where u.userid = b.userid order by awarded_date limit 1;

希望这可以帮助。

于 2013-05-27T16:03:59.953 回答
0

让我们把这个问题一分为二:

  1. 首先,您需要为每个人展示最近的腰带
  2. 然后你需要展示那些有腰带的人

那么,让我们开始吧。

步骤 1.a。每个用户的最新皮带记录

select b.*
from 
    belts as b
    inner join (
        select max(id) as maxId from belts group by userId
    ) as a on b.id = a.maxId

我假设该id领域始终是增量的。

步骤 1.b。将步骤 (1.a.) 与用户数据连接起来

select u.*, b.*
from 
    users as u
    inner join (
    select b.*
    from 
        belts as b
        inner join (
            select max(id) as maxId from belts group by userId
        ) as a on b.id = a.maxId
    ) as b on u.userId = b.userId

步骤 2. 选择具有给定腰带的所有用户

select u.*, b.*
from 
    users as u
    inner join (
    select b.*
    from 
        belts as b
        inner join (
            select max(id) as maxId from belts group by userId
        ) as a on b.id = a.maxId
    ) as b  on u.userId = b.userId
where
    b.belt_colour = 'brown'

希望这可以帮助

于 2013-05-27T16:06:17.117 回答