mysql子查询错误“where子句”中的未知列“tv.last\u time”

bkhjykvo  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(231)

当我使用mysql进行子查询时,我在where子句中得到未知列“tv.last\u time”,我该怎么办?在执行子查询时,我想使用外部条件来过滤不符合要求的记录

SELECT
    info_topic.*, b.newMessage
FROM
    info_topic
LEFT JOIN `info_topic_visit` AS tv ON tv.topic_id = info_topic.id
AND tv.user_id = 225
LEFT JOIN (
    SELECT
        p.topic_id,
        count(*) AS newMessage
    FROM
        info_post p
    WHERE
        p.create_time > tv.last_time
    GROUP BY
        p.topic_id
) AS b ON b.topic_id = info_topic.id
ORDER BY b.newMessage DESC

数据库架构:

CREATE TABLE `info_topic` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT '' COMMENT 'topic name',
  `summary` varchar(500) COLLATE utf8mb4_unicode_ci DEFAULT '' COMMENT 'summary`',
  `create_time` datetime DEFAULT NULL COMMENT '',
  `sort` int(11) DEFAULT '0' COMMENT '',
  PRIMARY KEY (`id`),
);

CREATE TABLE `info_topic_visit` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `topic_id` int(11) DEFAULT '0' COMMENT '',
  `user_id` int(11) DEFAULT '0' COMMENT '',
  `last_time` datetime DEFAULT NULL COMMENT '',
  PRIMARY KEY (`id`)
);
nwlls2ji

nwlls2ji1#

子查询的问题是 tv 别名在那里没有任何意义,因此不能引用该别名对应的表中的任何内容。一种方法是将子查询转换为select子句中的相关子查询:

SELECT
    i.*,
    (SELECT COUNT(*) FROM info_post p
     WHERE p.create_time > tv.last_time AND p.topic_id = i.id) AS newMessage
FROM info_topic i
LEFT JOIN info_topic_visit AS tv
    ON tv.topic_id = info_topic.id AND tv.user_id = 225
LEFT JOIN info_topic_member tm
    ON i.id = tm.topic_id AND
       tm.del_flag = 0    AND
       tm.apply_status = i.open_type AND
       tm.user_id = 225
WHERE
    i.del_flag = 0 AND
    i.id > 0       AND
    tm.id IS NOT NULL
ORDER BY
    newMessage DESC;

还有一种方法可以重构查询,这样就不需要使用效率低下的相关子查询。

相关问题