【问题标题】:Mysql -- UPDATE table SET column = SELECT COUNT(*) FROM ( SELECT * FROM table2 WHERE table2.id = table.id ) ) ImpossibleMysql -- UPDATE table SET column = SELECT COUNT(*) FROM (SELECT * FROM table2 WHERE table2.id = table.id)) 不可能
【发布时间】:2014-01-20 13:42:28
【问题描述】:

我有两个包含很多行的表,我需要为第一个 (table_1) 中的每一行维护“索引”信息。所以我写了一个查询,不直接使用 COUNT() [这很慢,很慢,很慢]。所以我尝试:

更新 table_1 SET table_1.column_3 = ( 选择计数(*)从( SELECT DISTINCT column_5 FROM table_2 WHERE table_2.id_t1 = table_1.id LIMIT 300 ) 吨 )

但是 MySQL 回答我 table_1.id 在 where 子句中是未知的 (#1054)

你知道如何在 where 子句中传递 table_1.id 吗?或者其他方式来实现我的目标?

谢谢你帮助我!

【问题讨论】:

    标签: php mysql innodb mariadb


    【解决方案1】:

    问题是因为table_1离内部查询太远了,使用:

    UPDATE table_1 SET table_1.column_3 = 
    (SELECT count(DISTINCT column_5) FROM table_2 WHERE table_2.id_t1 = table_1.id);
    

    我看到你正在使用 LIMIT,不确定你是否需要它,无论如何你可以模仿它:

    IF(count(distinct column_5)>300, 300, count(distinct column_5))

    【讨论】:

    • 您好,前面的SQL返回语法错误。 () 丢失。 table_1.column_3 = (SELECT COUNT .... ) 可以工作。
    • 我不确定是否理解您的回复 Ilya Bursov :我使用限制是为了不直接使用计数,这很慢。在您的查询中,如果我直接使用 count => 慢速请求...但我不理解您打印的第二个请求:IF(count(distinct column_5)>300, 300, count(distinct column_5)) 我该如何使用它?
    • @Robin 查询中的计数无论如何都会很慢,您可以尝试使用索引,但仍然 distinct 会很慢,可以使用 IF 构造而不是 count(distinct... 来提供相同的结果
    猜你喜欢
    • 2014-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多