我有两张桌子,第一张是雇员,其中包括' employee_id' company_id'和邮政编码。第二个表有company_id,company_postcode。
大量员工缺少邮政编码,或者由于平台客户中的错误,客户可以在邮政编码部分输入任何值,因此可能是街道名称,电话号码,出生日期甚至是000000之类的东西。 我想尽可能用company_post代码替换丢失/错误的邮政编码,如果公司邮政编码也丢失或错误,我需要将其替换为他们的同事邮政编码之一。 谢谢你,埃里克,我同意你的意见,很抱歉没有分享我的疑问,
SELECT
e.id,
e.company_id,
e.postcode,
c.reg_address_postcode,
postcode2,
CASE
WHEN
postcode NOT REGEXP '^[0-9]$'
OR postcode IS NOT NULL
OR postcode != ''
THEN
postcode
WHEN
postcode REGEXP '^[0-9]$'
OR postcode IS NULL
OR postcode = ''
AND c.reg_address_postcode NOT REGEXP '^[0-9]$'
OR c.reg_address_postcode IS NOT NULL
OR c.reg_address_postcode != ''
THEN
c.reg_address_postcode
WHEN
postcode REGEXP '^[0-9]$'
OR postcode IS NULL
OR postcode = ''
AND c.reg_address_postcode REGEXP '^[0-9]$'
OR c.reg_address_postcode IS NULL
OR c.reg_address_postcode = ''
THEN
postcode2
END AS new_postcode
FROM
employees e
LEFT JOIN
companies c ON e.company_id = c.id
LEFT JOIN
(SELECT
MAX(e.id),
e.company_id,
TRIM(postcode) postcode2,
c.reg_address_postcode
FROM
employees e
LEFT JOIN companies c ON e.company_id = c.id
WHERE
e.postcode NOT REGEXP '^[0-9]'
AND (e.postcode != ''
OR e.postcode IS NOT NULL)
AND (TRIM(e.postcode) < 4
OR TRIM(e.postcode) > 10)
GROUP BY company_id) o ON e.company_id = o.company_id
答案 0 :(得分:0)
我认为问题出在你的CASE
。 AND
优先于OR
。所以你的代码
WHEN postcode REGEXP '^[0-9]$'
OR postcode IS NULL
OR postcode = ''
AND c.reg_address_postcode NOT REGEXP '^[0-9]$'
OR c.reg_address_postcode IS NOT NULL
OR c.reg_address_postcode != ''
THEN
c.reg_address_postcode
被视为
WHEN postcode REGEXP '^[0-9]$'
OR postcode IS NULL
OR (postcode = ''
AND c.reg_address_postcode NOT REGEXP '^[0-9]$')
OR c.reg_address_postcode IS NOT NULL
OR c.reg_address_postcode != ''
THEN
c.reg_address_postcode
我肯定不是你想要的。尝试将括号放在OR
WHEN (postcode REGEXP '^[0-9]$'
OR postcode IS NULL
OR postcode = '')
AND (c.reg_address_postcode NOT REGEXP '^[0-9]$'
OR c.reg_address_postcode IS NOT NULL
OR c.reg_address_postcode != '')
THEN
c.reg_address_postcode