简体   繁体   English

SQL 服务器:来自多个表的 select

[英]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简而言之,我打算确定是否有一行 TS_Logou 小于 1 个月前的 Timestamp,如果 Dono_CID != -1

OBS: Accounts.ID = Logins.Jogador_ID OBS: Accounts.ID = Logins.Jogador_ID

OBS²: There are multiple records in the Logins table. OBS²:登录表中有多条记录。 I want to select the last one, in DESC order我要 select 最后一个,按 DESC 顺序

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.根据您的尝试,我了解到 TS_Logou < 1587524400 表示超过一个月。 I am trying to select the login with the maximum TS_Logou satisfying the filter condition.我正在尝试 select 满足过滤条件的最大 TS_Logou 登录。

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.在听到,我尝试 select max TS_Logou form Logins 为用户和该表加入帐户表。 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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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