一尘不染

这个MySQL查询有什么问题?SELECT * AS`x`,以后如何再次使用x?

sql

以下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子查询内部。

有任何想法吗?


编辑:
@Roland:谢谢您的评论。我有三个表actionsuserssites。该表actions包含一个userID字段,该字段对应于表中的一个条目users。该表(users)中的每个用户都有一个siteID。我正在尝试从actions表中选择最新操作,并将它们链接到userssites表,以找出谁执行了这些操作以及在哪个站点上执行了这些操作。希望有道理:)


阅读 140

收藏
2021-05-23

共1个答案

一尘不染

您要么需要将其包含在子查询中:

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

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)
2021-05-23