以下MySQL查询:
select `userID` as uID, (select `siteID` from `users` where `userID` = uID) as `sID`, from `actions` where `sID` in (select `siteID` from `sites` where `foo` = "bar") order by `timestamp` desc limit 100
传回错误:
Unknown column 'sID' in 'IN/ALL/ANY subquery'
我不明白我在做什么错。这个sID东西不应该是一列,而是我通过执行创建的“别名”(这叫什么?)(select siteID from users where userID = uID) as sID。而且它甚至不在IN子查询内部。
sID
(select siteID from users where userID = uID) as sID
IN
有任何想法吗?
编辑: @Roland:谢谢您的评论。我有三个表actions,users和sites。该表actions包含一个userID字段,该字段对应于表中的一个条目users。该表(users)中的每个用户都有一个siteID。我正在尝试从actions表中选择最新操作,并将它们链接到users和sites表,以找出谁执行了这些操作以及在哪个站点上执行了这些操作。希望有道理:)
actions
users
sites
userID
siteID
您要么需要将其包含在子查询中:
SELECT * FROM ( SELECT userID as uID, (select siteID from users where userID = actions.userID) as sID, FROM actions ) q WHERE sID IN (select siteID from sites where foo = "bar") ORDER BY timestamp DESC LIMIT 100
,或者,最好将其重写为 JOIN
JOIN
SELECT a.userId, u.siteID FROM actions a JOIN users u ON u.userID = a.userID WHERE siteID IN ( SELECT siteID FROM sites WHERE foo = 'bar' ) ORDER BY timestamp DESC LIMIT 100
创建以下索引:
actions (timestamp) users (userId) sites (foo, siteID)