I have 2 tables - ACCOUNTS
and USERS
:
ACCOUNTS:
CREATE TABLE `ACCOUNTS` (
`pk` bigint(10) unsigned NOT NULL AUTO_INCREMENT,
`user_id` varchar(9) NOT NULL,
`primary` varchar(1) NOT NULL DEFAULT 'N',
`edit_on` bigint(10) unsigned DEFAULT NULL,
`status` varchar(1) NOT NULL DEFAULT 'A',
PRIMARY KEY (`pk`) USING BTREE
) ENGINE=MyISAM AUTO_INCREMENT=1234567890 DEFAULT CHARSET=latin1
USERS:
CREATE TABLE `USERS` (
`user_id` bigint(9) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1
if edit_on
contains a non-null value, it means the entry is an edit on an existing entry, whose pk
is contained in edit_on
.
Here's what I want to do:
- For every
user_id
inACCOUNTS
, there should be a matchinguser_id
inUSERS
. - If
edit_on
isnot null
, there should exist an entry inACCOUNTS
with it'spk
equal to this (input)edit_on
anduser_id
equal to this (input)user_id
. And for that (old) entry,status
should be set toE
. - If
primary = 'Y'
, then for other rows inACCOUNTS
with the particularuser_id
,primary
should be set to'N'
After experimenting a hell lot with different queries (using ON DUPLICATE UPDATE
etc.), I still cant find a solution. Please help, as I've been working on this for 2 full days. Thanks in advance.
EDIT
Here's something along the lines of what i've tried so far:
insert into ACCOUNTS
case
when edit_on is null
then
select null, '222222222', 'N', null)
else
select null, '222222222', 'N', pk)
from ACCOUNTS
where '222222222' = user_id and '2147483680' = pk
select pk, '222222222', 'N', pk)
on duplicate key update status='E'
end
I haven't done anything about primary
yet PLUS this one's not the solution :D