删除具有特定计数的mysql相关记录

时间:2013-02-28 23:37:48

标签: mysql

我需要删除2012年之前创建的表'人'中属于酒店ID'1'的记录,并且在相关表'taskinstance'中只有1条记录。这些表以这种方式相关:people.id = taskinstance.idClient。我想出了下面的语法错误。

DELETE people FROM taskinstance people 
INNER JOIN 
    (SELECT * 
     FROM taskinstance
    WHERE substring(people.dateCreated,1,4) < 2012 and people.idHotel = '1'  
     GROUP BY taskinstance.idClient 
     HAVING COUNT(*) = 1) taskinstance 
ON people.id = taskinstance.idClient

如果我只想查看记录,以下工作:

SELECT *
FROM people
INNER JOIN taskinstance ON people.id = taskinstance.idClient
WHERE substring(people.dateCreated,1,4) < 2012 and people.idHotel = '1'
GROUP BY people.id
HAVING COUNT(1) = 1

感谢您提供任何帮助。

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

 DELETE FROM people WHERE people.id IN 
 (SELECT people.id
 FROM people
 INNER JOIN taskinstance ON people.id = taskinstance.idClient
 WHERE substring(people.dateCreated,1,4) < 2012 and people.idHotel = '1'
 GROUP BY people.id
 HAVING COUNT(*) = 1)

<击> 编辑:在我自己的数据库上测试,这个被拒绝在WHERE子句中使用与DELETE子句中相同的表。

或者这个:

 DELETE people FROM people
 INNER JOIN (
    SELECT people.id
    FROM people
    INNER JOIN taskinstance ON people.id = taskinstance.idClient
    WHERE substring(people.dateCreated,1,4) < 2012 and people.idHotel = '1'
    GROUP BY taskinstance.idClient
    HAVING COUNT(*) = 1
    ) p
 ON p.id = people.id

编辑:我在我自己的数据库中测试了一个几乎相同的查询(只有我自己的表),并且查询中没有语法错误。

请发布语法错误的全文,以便我们可以追踪问题,尤其是它所说的部分,"... for the right syntax to use near 'something something something' on line X." something something部分是排查问题的最重要部分。例如,如果它显示"near '' on line 6",那么你几乎肯定没有逃过那个1周围的单引号。