如何在SQL中的两个表之间进行连接?

时间:2018-02-12 14:56:33

标签: mysql

我有两张桌子

PC
----------------------------------
| PCID   | PCName| IPAdd | CLnum |
----------------------------------
|   1    |  PC1  |192.X.1|   1   |
|   2    |  PC2  |192.x.2|   1   |
|   3    |  PC3  |192.x.3|   1   |
----------------------------------

Date
----------------------------------
| DateID |  Date | Time |  PCID  |
----------------------------------
|    1   |2/12/18| 17:05|    1   |
|    2   |2/12/18| 17:14|    1   |
|    3   |2/12/18| 17:18|    1   |
|    4   |2/12/18| 17:36|    1   |
|    5   |2/12/18| 18:23|    2   |
|    6   |2/12/18| 18:26|    2   |
|    7   |2/12/18| 18:28|    3   |
----------------------------------

SELECT t1.PCID, t1.PCName, t1.IPAdd, t1.CLnum, t2.date, t2.time 
FROM pc t1 JOIN date t2 ON t2.PCID = t1.PCID 
WHERE t2.PCID= t1.PCID and t2.date>=date order by time desc limit 1

我尝试使用上面的查询,但我需要的结果是这样的:

example:
-------------------------------------------------
| PCID | PCName | IPAdd | CLnum |  Date  | Time |
-------------------------------------------------
|  1   |   PC1  |192.x.1|   1   |02/12/18| 17:36|
|  2   |   PC2  |192.x.2|   1   |02/12/18| 18:26|
|  3   |   PC3  |192.x.3|   1   |02/12/18| 18:28|
-------------------------------------------------

我要做的是获取每台PC在最后一次使用的时间。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

似乎您正在寻找值的最大值(时间):

SELECT   t1.pcid, 
         t1.pcname, 
         t1.ipadd, 
         t1.clnum, 
         t2.date, 
         Max(t2.time ) 
FROM     pc t1 j oin date t2 
ON t2.pcid = t1.pcid 
WHERE    t2.pcid= t1.pcid 
AND      t2.date>=date 
GROUP BY t1.pcid, 
         t1.pcname, 
         t1.ipadd, 
         t1.clnum, 
         t2.date 
ORDER BY t1.pcid