我有6个mysql数据库,其表名相同,例如users_table,字段为email_address,现在我想从任何一个数据库表中丢失所有6个db中的email_address。
请给我一些建议。
答案 0 :(得分:0)
此选项会选择其中一个数据库中缺少的所有电子邮件,并指出它们所在的数据库。
SELECT email, GROUP_CONCAT(db_Name) AS emailIsOnlyIn FROM (
SELECT 'db1' as db_Name, email FROM db1.yourTable
UNION ALL
SELECT 'db2' as db_Name, email FROM db2.yourTable
UNION ALL
SELECT 'db3' as db_Name, email FROM db3.yourTable
UNION ALL
SELECT 'db4' as db_Name, email FROM db4.yourTable
UNION ALL
SELECT 'db5' as db_Name, email FROM db5.yourTable
UNION ALL
SELECT 'db6' as db_Name, email FROM db6.yourTable
) subquery_alias
GROUP BY email
HAVING COUNT(DISTINCT db_name) < 6;
如果您想知道哪个数据库丢失了电子邮件,那就更复杂了:
SELECT
*
FROM (
SELECT email FROM db1.yourTable
UNION
SELECT email FROM db2.yourTable
UNION
SELECT email FROM db3.yourTable
UNION
SELECT email FROM db4.yourTable
UNION
SELECT email FROM db5.yourTable
UNION
SELECT email FROM db6.yourTable
) sq,
( SELECT 'db1' as db_Name2
UNION ALL
SELECT 'db2' as db_Name2
UNION ALL
SELECT 'db3' as db_Name2
UNION ALL
SELECT 'db4' as db_Name2
UNION ALL
SELECT 'db5' as db_Name2
UNION ALL
SELECT 'db6' as db_Name2
)dummy
WHERE NOT EXISTS (SELECT 1 FROM (
SELECT 'db1' as db_Name, email FROM db1.yourTable
UNION ALL
SELECT 'db2' as db_Name, email FROM db2.yourTable
UNION ALL
SELECT 'db3' as db_Name, email FROM db3.yourTable
UNION ALL
SELECT 'db4' as db_Name, email FROM db4.yourTable
UNION ALL
SELECT 'db5' as db_Name, email FROM db5.yourTable
UNION ALL
SELECT 'db6' as db_Name, email FROM db6.yourTable
) subquery_alias
WHERE sq.email = subquery_alias.email AND subquery_alias.db_Name = dummy.db_Name2
)