我有以下查询:
SELECT
*,
(SELECT locked FROM forum_topics t WHERE t.id = topicid) as topiclocked,
forum_subtopics.locked as stlocked
FROM forum_subtopics
WHERE topicid = 1;
我想使用字段topiclocked
和stlocked
来创建名为locked
的第三个自定义列。我尝试了以下内容,但MySQL告诉我topiclocked
不存在:
SELECT
*,
(SELECT locked FROM forum_topics t WHERE t.id = topicid) as topiclocked,
forum_subtopics.locked as stlocked,
(topiclocked || stlocked) as locked
FROM forum_subtopics
WHERE topicid = 1;
未知专栏' topiclocked'在'字段列表'
如何以实际工作的方式创建第三个coloumn?
答案 0 :(得分:1)
您不能在同一alias name (topiclocked)
声明中使用select
。将查询设为sub-select
并在outer query
中进行连接。试试这个。
SELECT *,
( topiclocked || stlocked ) AS locked
FROM (SELECT *,
(SELECT locked
FROM forum_topics t
WHERE t.id = topicid) AS topiclocked,
forum_subtopics.locked AS stlocked
FROM forum_subtopics
WHERE topicid = 1) a;
答案 1 :(得分:1)
您可以在select
- 部分中分配变量,就像这样
SELECT
*,
@topiclocked:=(SELECT locked FROM forum_topics t WHERE t.id = topicid) as topiclocked,
@stlocked:=forum_subtopics.locked as stlocked,
(@topiclocked || @stlocked) as locked
FROM forum_subtopics
WHERE topicid = 1;
http://sqlfiddle.com/#!2/572453/1
我会用JOIN
重写该查询,这样您就不必执行子查询,并且您可以从两个表中获得locked
。
SELECT s.*,
t.locked as topiclocked,
s.locked as stlocked,
(t.locked || s.locked) as locked
FROM forum_subtopics s
JOIN forum_topics t on (s.topicid = t.id)
WHERE topicid = 1;
答案 2 :(得分:1)
select
中定义的别名不能用于select
或where
子句。通常,您将使用子查询或公用表表达式(但不在MySQL中)来解决此问题。但是,MySQL实现了子查询,因此这会对性能产生影响。
在您的情况下,您可以将查询重写为:
SELECT s.*, t.locked as topiclocked, s.locked as stlocked,
(t.locked || s.locked) as locked
FROM forum_subtopics s JOIN
forum_topics t
ON t.id = s.topicid
WHERE s.topicid = 1;
如果您的子主题没有主题,则可能需要left join
。我猜你的数据不是这种情况,所以我只是使用内连接。