我正在尝试对两个查询进行INNER JOIN。 如果我对第一个组件有一个广泛的SELECT语句,它可以正常工作。 如果我尝试向第一个组件添加WHERE ...,我会收到一个无法提供信息的语法错误,我不知道为什么。
这是有效的,但是很慢,因为我的桌子很大(〜1mil行)
SELECT a.RoomNum, a.EventName, a.EventStatus, a.EventDateTime FROM eventtable a
INNER JOIN
(
SELECT `RoomNum`, eventname, MAX(`EventDateTime`) as MT
FROM `eventtable`
WHERE eventname = "DND"
Group BY RoomNum
) b
ON a.RoomNum = b.RoomNum and a.EventDateTime = b.MT and a.eventname = b.eventname
但我真正需要的是:
SELECT a.RoomNum, a.EventName, a.EventStatus, a.EventDateTime from eventtable WHERE a.EventName = "DND" a
INNER JOIN
(
SELECT `RoomNum`, eventname, MAX(`EventDateTime`) as MT
FROM `eventtable`
where eventname = "DND"
Group by RoomNum
) b
on a.RoomNum = b.RoomNum and a.EventDateTime = b.MT and a.eventname = b.eventname
我想过将结果分配给一个表,但实际上并不想生成一个表然后放下它以确保下次进行查询时,将不会有表存在。
感谢。
答案 0 :(得分:0)
您的查询应该是
SELECT a.RoomNum, a.EventName, a.EventStatus, a.EventDateTime from eventtable a
INNER JOIN
(
SELECT `RoomNum`, eventname, MAX(`EventDateTime`) as MT
FROM `eventtable`
where eventname = "DND"
Group by RoomNum
) b
on a.RoomNum = b.RoomNum and a.EventDateTime = b.MT and a.eventname = b.eventname
WHERE a.EventName = "DND"
观察 where
即将结束。
答案 1 :(得分:0)
Where子句出现在END ...然后你将它放在from和INNER之间,所以它会导致语法错误...所以你可以做这样的事情
SELECT a.RoomNum, a.EventName, a.EventStatus, a.EventDateTime from eventtable a
INNER JOIN
(
SELECT `RoomNum`, eventname, MAX(`EventDateTime`) as MT
FROM `eventtable`
where eventname = "DND"
Group by RoomNum
) b
on a.RoomNum = b.RoomNum and a.EventDateTime = b.MT and a.eventname = b.eventname
WHERE a.EventName = "DND"
或者如果你不想使用where子句,你可以像这样直接检查连接中的条件..
SELECT a.RoomNum, a.EventName, a.EventStatus, a.EventDateTime from eventtable a
INNER JOIN
(
SELECT `RoomNum`, eventname, MAX(`EventDateTime`) as MT
FROM `eventtable`
where eventname = "DND"
Group by RoomNum
) b
on a.RoomNum = b.RoomNum and a.EventDateTime = b.MT and a.eventname = b.eventname and a.EventName = "DND"
答案 2 :(得分:0)
首先,JOIN可以在两个表上。在你写的时候,你不应该在这两个上添加条件。如果您愿意,最后添加它们。
将where子句放在最后,它将起作用。