MYSQL需要连接2个具有多个结果的表

时间:2013-02-27 18:17:18

标签: mysql

使用下面的2个表格,我想显示一个名单列表,其下一个可用时间显示在他们的名字旁边。每个名字只有1个结果。你能帮我吗? 谢谢Bobby

user table
|  user_ID  |  name   
|  1        |   Smith  
|  2        |   Jones 

times_available
|    ID    |   user_ID  | time_avail |
|        1 |   2        |   01:30    |
|        2 |   2        |   02:30    |
|        3 |   3        |   02:30    |
|        4 |   3        |   03:30    |
|        5 |   3        |   04:30    |

显示每个名称的下一个可用时间

|  user_ID  |  time   |
|    Smith  |   02:30 |
|    Jones  |   02:30 |

@Clodoaldo有一个很好的答案,但我还需要显示没有即将到来的time_avail的名字

2 个答案:

答案 0 :(得分:2)

select u.name, min(t.time_avail)
from
    user_table u
    inner join
    times_available t on u.user_id = t.user_id
where t.time_avail > current_time
group by u.user_id

答案 1 :(得分:0)

你可以这样做

SELECT 
    u.user_ID,
    u.name,
    ta.NewTime
FROM user AS u
LEFT JOIN (
       SELECT r.* , lta.time_avail AS `NewTime` FROM times_available as r
       LEFT JOIN (SELECT * FROM times_available LIMIT 1,69596585953484) AS lta
          ON lta.ID = (SELECT MIN(ID) FROM times_available WHERE ID > r.ID GROUP BY r.ID limit 1)
) AS ta ON ta.user_ID = u.user_ID 
WHERE ta.NewTime IS NOT NULL
GROUP BY u.user_ID 

Fiddle Demo