我正在尝试从2个不同的表中获取数据,这些表在MySQL中具有完全相同的记录。这是示例数据
TABLE 1
----------------------------------
ID NAME MEMBER SMS_MEMBER
1 JOHN YES NO
2 JOY NO NO
3 SMITH NO YES
4 ANDRES YES YES
TABLE 2
----------------------------------
ID NAME MEMBER SMS_MEMBER
1 JOHN YES NO
2 JOY NO YES
3 SMITH NO YES
4 ANDRES YES YES
这是我的逻辑查询
SELECT * FROM TABLE1, TABLE2
WHERE
TABLE1.ID = TABLE2.ID
AND
TABLE1.NAME = TABLE2.NAME
AND
TABLE1.EMAIL_MEMBER = TABLE2.EMAIL_MEMBER
AND
TABLE1.SMS_MEMBER = TABLE2.SMS_MEMBER;
预期结果应该是
----------------------------------
ID NAME MEMBER SMS_MEMBER
1 JOHN YES NO
3 SMITH NO YES
4 ANDRES YES YES
由于下面的记录在SMS_MEMBER字段上具有不同的值,因此将其排除在外
EXCLUDED RECORD
----------------------------------
ID NAME MEMBER SMS_MEMBER
2 JOY NO YES
如果有人建议对此进行查询,那会很棒吗?
答案 0 :(得分:2)
您当前的查询实际上应该可以正常工作,尽管我会使用 explicit 内部联接来编写它:
SELECT DISTINCT t1.*
FROM TABLE1 t1
INNER JOIN TABLE2 t2
ON t1.ID = t2.ID AND
t1.NAME = t2.NAME AND
t1.MEMBER = t2.MEMBER AND
t1.SMS_MEMBER = t2.SMS_MEMBER;
只是为了好玩,这是另一种查询方法,使用并集后面加上联合:
SELECT ID, NAME, MEMBER, SMS_MEMBER
FROM
(
SELECT ID, NAME, MEMBER, SMS_MEMBER FROM TABLE1
UNION ALL
SELECT ID, NAME, MEMBER, SMS_MEMBER FROM TABLE2
) t
GROUP BY ID, NAME, MEMBER, SMS_MEMBER
HAVING COUNT(*) = 2;
条件HAVING COUNT(*) = 2
确保只有出现在两个表中的相同记录才最终出现在结果集中。
答案 1 :(得分:0)
您想要的是intersect
,但是MySQL不支持它。
要完全重叠,您的代码基本上应该可以工作,但是我建议:
SELECT t1.*
FROM TABLE1 t1 JOIN
TABLE2 t2
USING (ID, NAME, EMAIL_MEMBER, SMS_MEMBER);