我有两个相似的表 table_a 和 table_b table_a 是我当前的数据,我需要使用临时表 table_b 更新此信息。两者之间的唯一区别是 table_a 有一个 table_b 没有的密码字段。
我正在尝试做一些事情。
1.Compare the data based on the "user_id" field.
2. If there is a user_id not found in table_b but there is one in table_a remove that row in table_a
3. If there is a user_id in table_b that is not found in table_a add that row of data to table_a
4. If the user_id is found in both then check two of the fields "email" and "job_code" and make sure they are both whatever table_b says.
我应该按照上面编号的顺序在单独的 MySQL 语句中执行此操作吗?以下是我对上述陈述的尝试。非常感谢任何帮助或故障排除。谢谢!
语句 1:
SELECT * FROM table_a
WHERE table_a.user_id
NOT IN (
SELECT table_b.user_id
FROM table_b
WHERE table_a.user_id=table_b.user_id
) // But how do I delete those records that are selected?
声明 2:
SELECT * FROM table_b
WHERE table_b.user_id
NOT IN (
SELECT table_a.user_id
FROM table_a
WHERE table_a.user_id=table_b.user_id
) //How do I Insert these records that I have in table_b but not in table_a
声明 3:
SELECT email FROM table_b
WHERE table_b.user_id = table_a.user_id,
AND table_b.email != table_a.email //now I need to update table_a with the emails from table_b
最佳答案
声明#1
DELETE A.*
FROM table_a A
LEFT JOIN table_b B
USING (user_id)
WHERE B.user_id IS NULL;
声明 #2
INSERT INTO table_b (column1,column2,...,columnN)
SELECT A.column1,A.column2,...,A.columnN
FROM table_b B LEFT JOIN table_a A
USING (user_id)
WHERE A.user_id IS NULL;
声明 #3
UPDATE table_a A INNER JOIN table_b B USING (user_id)
SET A.email = B.email,A.job_code = B.job_code;
更新 2012-06-19 11:54 EDT
A 和 B 只是表的别名。
例如,语句 #3 的查询可以像下面这样写:
UPDATE table_a as A INNER JOIN table_b as B USING (user_id)
SET A.email = B.email,A.job_code = B.job_code;
或者没有任何别名,像这样:
UPDATE table_a INNER JOIN table_b USING (user_id)
SET table_a.email = table_b.email,table_a.job_code = table_b.job_code;
关于mysql - 比较两个表 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11103208/