简体   繁体   中英

SQL Server : select from multiple tables

Table Accounts :

+----+------+----------+
| ID | Nick | Dono_CID |
+----+------+----------+
|  2 | Bart |        3 |
+----+------+----------+

Table Logins :

+------------+------------+
| Jogador_ID | TS_Logou   |
+------------+------------+
|          2 | 1590116475 |
|          2 | 1590118258 |
+------------+------------+

In short, I intend to identify if there is a row with TS_Logou smaller than the Timestamp of 1 month ago, and if Dono_CID != -1

OBS: Accounts.ID = Logins.Jogador_ID

OBS²: There are multiple records in the Logins table. I want to select the last one, in DESC order

My attempt:

SELECT 
    ct.Nick, 
    ct.Dono_CID 
FROM 
    Contas AS ct 
INNER JOIN 
    Logins AS lg ON lg.Jogador_ID = ct.ID 
WHERE 
    ct.Dono_CID != -1 
    AND lg.TS_Logou < 1587524400 
GROUP BY 
    lg.Jogador_ID 
ORDER BY 
    lg.TS_Logou DESC 
LIMIT 1

From your attempt, I understand that TS_Logou < 1587524400, means older than one month. I am trying to select the login with the maximum TS_Logou satisfying the filter condition.

SELECT TOP 1 a.Id, a.Nick, a.Dono_CID
FROM Logins as l
Inner Join Account as a
a.Id = l.Jogador_Id 
WHERE a.Dono_CID <> -1 
AND a.TS_Logou < 1587524400
ORDER BY l.TS_Logou DESC

in hear, I try to select max TS_Logou form Logins for the user and that table joins with the Account table. this works for me

SELECT 
 ac.Nick, 
 ac.Dono_CID 
FROM 
    Account AS ac 
INNER JOIN 
 (SELECT l.Jogador_ID,MAX(l.TS_Logou) FROM Logins AS l 
   WHERE DATE(l.TS_Logou) < DATEADD(month, -1, GETDATE()) 
   GROUP BY l.Jogador_ID) AS lg 
 ON lg.Jogador_ID = ac.ID 
WHERE 
 ac.Dono_CID <> -1 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM