我有两个相互关联的表,我想只从一个表中删除记录。表格结构如下
Table : Users
userunique, active, unSubscribed
Table : userBilling
userunique, billCreatedDate,billstatus
我想删除那些不再具有以下条件的用户的帐单。
billcreateddate < 2011-12-30
billstatus=2 //pending
active='0'
unSubscribed<'2011-12-30'
我写了一个查询,但这不是我的预期。我想仅从userBilling表而不是用户表
中删除记录select * from userBilling ubill, Users user
WHERE ubilll.userUnique=user.userUnique
AND ubill.billCreatedDate<'2011-12-30'
AND ubill.billstatus = '2'
AND ((user.active = '0') AND (user.unsubscribed>'2011-01-01')
AND user.unSubscribed<'2011-12-30'))
但我猜上面的查询包括两个表的结果。请提出建议!
谢谢,
答案 0 :(得分:3)
DELETE a
FROM userBilling a
INNER JOIN users b
ON a.auserUnique = b.userUnique
WHERE billcreateddate < 2011-12-30 OR
billstatus = 2 OR
active = 0 OR
unSubscribed < '2011-12-30'
如果您希望所有条件为真 ,请将OR
更改为AND
。
答案 1 :(得分:1)
这应该有效。你应该总是明确地加入你的联接。那样你就不会感到惊讶了。
DELETE ubill
FROM userBilling ubill
JOIN Users u
ON (ubill.userUnique=u.userUnique)
WHERE ubill.billCreatedDate<'2011-12-30'
AND ubill.billstatus = '2'
AND ((u.active = '0') AND (u.unsubscribed>'2011-01-01')
AND u.unSubscribed<'2011-12-30'))
答案 2 :(得分:0)
尝试这样做
DELETE ubill
FROM userBilling ubill
INNER JOIN Users
ON ubill.userUnique=user.userUnique
WHERE
ubill.billCreatedDate<'2011-12-30'
AND ubill.billstatus = '2'
AND user.active = '0'
AND user.unsubscribed>'2011-01-01'
AND user.unSubscribed<'2011-12-30'