mysql子查询错误“ where子句”中的未知列“ tv.last_time”

时间:2018-11-28 06:21:05

标签: mysql subquery

当我使用mysql进行子查询时,在“ where子句”中得到Unknown列“ tv.last_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`)
);

1 个答案:

答案 0 :(得分:1)

子查询的问题是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;

也许还有一种重组查询的方法,这样您就不必使用效率不高的相关子查询。