我需要将以下三个SELECT语句合并为一个SQL语句:
1. SELECT TotalTime FROM Session WHERE device_uid = ${my_uid} ORDER BY StartTime DESC LIMIT 1;
2. SELECT HoursAtService FROM Service WHERE device_uid = ${my_uid} ORDER BY StartTime DESC LIMIT 1;
3. SELECT ServiceHours FROM Type WHERE type_uid = ${my_type_uid};
最好,我希望将结果作为一行包含以下字段:
Result:
----------------------------------------------------------------
uid, TotalTime, HoursAtService, ServiceHours
我正在考虑可能需要进行内部联接,但是我不确定100%如何进行内部联接。像这样:
SELECT uid, TotalTime, HoursAtService, ServiceHours FROM Device AS t1 INNER JOIN (... -> continues
在表之间进行联接很容易,但是如何对多个表使用多个WHERE子句进行联接?
有人可以告诉我如何构造查询吗?
编辑-表模式
Device:
---------------------
device_uid, type_uid, ....
Session:
---------------------
device_uid, session_uid, TotalTime, StartTime, EndTime, SessionTime
Service:
---------------------
device_uid, service_uid, StartTime, EndTime, HoursAtService
Type:
---------------------
type_uid, Name, ServiceHours
答案 0 :(得分:0)
您可以在单个查询中合并上面的单个查询,例如在MYSQL查询下面:
SELECT Session.uid, Session.TotalTime, Service.HoursAtService, ServiceHours.ServiceHours
FROM Session
JOIN Service ON Service.udi = Session.uid
JOIN ServiceHours ON ServiceHours.type_uid = Session.uid
WHERE Session.uid = ${my_uid}
ORDER BY Session.StartTime DESC LIMIT 1;
更改相关表中的列名。
答案 1 :(得分:0)
尝试这样的事情:
SELECT ${my_uid} AS uid,
(SELECT TotalTime FROM Session WHERE uid = ${my_uid} ORDER BY StartTime DESC LIMIT 1) AS TotalTime,
(SELECT HoursAtService FROM Service WHERE udi = ${my_uid} ORDER BY StartTime DESC LIMIT 1) AS HoursAtService,
(SELECT ServiceHours FROM Type WHERE type_uid = ${my_type_uid) AS ServiceHours
答案 2 :(得分:0)
您可以使用以下查询来实现您提到的内容,由于服务和会话都是SQL关键字,因此我也考虑了关键字的方括号。
SELECT
[Device].Type_uid AS DeviceTypeId, [Device].Device_uid AS DeviceId, [Session].TotalTime, [Service].HoursAtService, [Type].ServiceHours
FROM
[Session] INNER JOIN [Device] ON [Session].Device_uid = [Device].Device_uid
[Service] INNER JOIN [Device] ON [Service].Device_uid = [Device].Device_uid
[Type] INNER JOIN [Device] ON [Type].Type_uid = [Device].Type_uid
WHERE
[Device].Type_uid = ${my_type_uid} AND [Device].Device_uid = ${my_uid}