嗨,我不善于提出问题。我会尽我的全力。我正在创建一个网站,我的问题与网站相关的查询有关。这是我当前的查询。
SELECT
GPS_modem.vehicle_no,
vehicle_log.longitude,
vehicle_log.latitude,
vehicle_log.timestamp
FROM
vehicle_log,
GPS_modem
WHERE
GPS_modem.modem_ID = vehicle_log.modem_ID
ORDER BY
timestamp desc
我要显示的是具有vehicle_log
表中最新时间戳的条目,其中modem_ID
表中的GPS_modem
与来自{modem_ID
的{{1}}匹配1}}表。
我尝试使用vehicle_log
,但我没有工作。我尝试使用DISTINCT
函数时遇到错误。希望你能理解我的问题,如果那时请帮助我。提前感谢你。
答案 0 :(得分:4)
您可以使用相关子查询:
SELECT
m.vehicle_no,
l.longitude,
l.latitude,
l.timestamp
FROM
vehicle_log AS l,
GPS_modem AS m
WHERE
m.modem_ID = l.modem_ID
AND l.timestamp = (
SELECT MAX(timestamp) FROM vehicle_log WHERE modem_ID = l.modem_ID
)
SELECT
m.vehicle_no,
latest.longitude,
latest.latitude,
latest.timestamp
FROM
GPS_modem AS m,
(
SELECT
modem_ID,
longitude,
latitude,
timestamp
FROM
vehicle_log AS l
WHERE
timestamp = (
SELECT MAX(timestamp) FROM vehicle_log WHERE modem_ID = l.modem_ID
)
) AS latest
WHERE
m.modem_ID = latest.modem_ID
答案 1 :(得分:1)
取决于数据库,
SELECT TOP 1 GPS_modem.vehicle_no, vehicle_log.longitude, vehicle_log.latitude, vehicle_log.timestamp from vehicle_log,GPS_modem where GPS_modem.modem_ID = vehicle_log.modem_ID order by timestamp desc
可以在SQL Server上运行。
答案 2 :(得分:0)
在MySQL中,您可以在查询结尾使用“限制1”。
答案 3 :(得分:0)
这可能不是最好的方法。
但是,既然你订购了结果,你可以使用LIMIT。
SELECT GPS_modem.vehicle_no, vehicle_log.longitude, vehicle_log.latitude, vehicle_log.timestamp from vehicle_log,GPS_modem where GPS_modem.modem_ID = vehicle_log.modem_ID order by timestamp desc LIMIT 1
还有其他解决方案(可能更好),但这是一个选择。
答案 4 :(得分:0)
以下是使用SQL Server的示例。它使用相关子查询,其优点是使用modem_ID执行匹配,而不是使用时间戳的相等匹配。
CREATE TABLE #GPS_modem
(
ID INT IDENTITY(1,1) PRIMARY KEY,
vehicle_no VARCHAR(10)
)
CREATE TABLE #vehicle_log
(
ID INT IDENTITY(1,1) PRIMARY KEY,
modem_ID INT,
longitude INT,
latitude INT,
[timestamp] DATETIME DEFAULT GETDATE()
)
INSERT INTO #GPS_modem
SELECT 'ABC123' UNION ALL SELECT 'XYZ123'
INSERT INTO #vehicle_log
SELECT 1,234,543,GETDATE()
UNION all
SELECT 2,4342,432234,GETDATE()
UNION all
SELECT 1,4322,432,DATEADD(DAY,-1,GETDATE())
UNION all
SELECT 2,6336,5324,DATEADD(DAY,-1,GETDATE())
SELECT * FROM #GPS_modem
SELECT * FROM #vehicle_log
SELECT
vehicle_no,
longitude,
latitude,
[timestamp]
FROM
#GPS_modem A
inner join #vehicle_log B on
A.ID = B.modem_ID
WHERE B.ID IN
(
SELECT TOP 1 ID
FROM #vehicle_log
WHERE modem_ID = A.ID
ORDER BY [timestamp] DESC
)
DROP TABLE #GPS_modem
DROP TABLE #vehicle_log
干杯,约翰
答案 5 :(得分:0)
在Oracle中:
SELECT
GPS_modem.vehicle_no,
vehicle_log.longitude,
vehicle_log.latitude,
vehicle_log.timestamp
FROM
(
SELECT v.*, ROW_NUMBER() OVER (PARTITION BY modem_id ORDER BY timespace DESC) AS rn
) l, GPS_modem m
WHERE
l.rn = 1
AND m.modem_ID = l.modem_ID
在MySQL中:
SELECT *
FROM (
SELECT DISTINCT g.id AS gid, (
SELECT l.modem_id
FROM vehicle_log l
WHERE l.modem_id = g.modem_id
ORDER BY timestemp DESC
LIMIT 1
) lid
), vehicle_log lo, GPS_modem go
WHERE lo.modem_id = lid
AND go.modem_id = lo.modem_id