mysql每个派生表必须有自己的DELETE查询别名

时间:2016-06-12 15:16:28

标签: mysql

我找到了答案,但它引用的是SELECT而不是DELETE,我不确定如何在这种情况下实现给定的答案。

通过下面的查询,我想删除除最后10个最新值(由id_lv定义)以外的所有值,但仅限一个用户。

DELETE FROM last_viewed
  WHERE id_lv <= (
    SELECT id_lv
    FROM (
      SELECT id_lv
      FROM last_viewed
      WHERE user_id_lv = '$user_id'
      ORDER BY id_lv DESC
      LIMIT 1 OFFSET 10
    )
  )

当我运行它时,我得到Every derived table must have its own alias

2 个答案:

答案 0 :(得分:1)

您必须在DELETE语句的子查询使用的派生表中使用别名:

DELETE FROM last_viewed
  WHERE id_lv <= (
    SELECT id_lv
    FROM (
      SELECT id_lv
      FROM last_viewed
      WHERE user_id_lv = '$user_id'
      ORDER BY id_lv DESC
      LIMIT 1 OFFSET 10
    ) AS t -- You need an alias here
  )

答案 1 :(得分:1)

使用表格(FROM)<和p>的别名和别名

DELETE FROM last_viewed
  WHERE id_lv in  (
    SELECT  t.id_lv
    FROM (
      SELECT id_lv
      FROM last_viewed
      WHERE user_id_lv = '$user_id'
      ORDER BY id_lv DESC
      LIMIT  10
    ) as t
  )