mysql - 比较两个表 MySQL

标签 mysql join compare

我有两个相似的表 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/

相关文章:

Javascript:跨多个数组查找共享值

python - python fetchall()中的MySQL死锁

php - 基于 PHP/JavaScript 的安全、可定制、开源聊天引擎,适用于所有流行的浏览器

MySQL查询左连接问题

sql - 最大化 from 子句中的联接并最小化 where 子句中的联接 : true?

php - 字符串与不同 COLLATION 的比较

javascript - 比较 2 个数组 - 一个包含字符串,另一个包含数字。重复字符串的个数之和

mysql - 条目中以逗号分隔的循环子字符串

java - 将容器连接到mysql数据库并访问它

MySQL创建连接两个表的 View