如何从2个表中检索不常见的值?

时间:2011-08-02 07:05:38

标签: mysql sql-server

我有以下2个表t1,t2,其值为

t1        t2
1         4
2         2
3         3

现在我要输出

1 
4

如何在选择查询中获得此输出?

3 个答案:

答案 0 :(得分:5)

这将为t1中的t2中的每个项目以及t2t1中不存在的select t1.id from t1 left join t2 on t2.id = t1.id where t2.id is null union all select t2.id from t2 left join t1 on t1.id = t2.id where t1.id is null 中的每个项目提供:

id

(我假设每个表中的字段名称都被命名为select coalesce(t1.id, t2.id) from t1 full outer join t2 on t2.id = t1.id where t1.id is null or t2.id is null ,只是为了能够针对表编写查询。)

另一种方式是:

{{1}}

答案 1 :(得分:0)

您可以在MySql中使用Joins继续并获取结果。

这对你有所帮助 http://www.techrepublic.com/article/sql-basics-query-multiple-tables/1050307

答案 2 :(得分:0)

另一种方式。只计算他们。

如果每个表的值是唯一的

,则此方法有效
SELECT
    CombinedValue
FROM
    (
    SELECT t1 AS CombinedValue FROM t1
    UNION ALL
    SELECT t2 FROM t2
    ) foo
GROUP BY
    CombinedValue
HAVING
    COUNT(*) = 1

如果每张桌子不唯一

SELECT
    CombinedValue
FROM
    (
    SELECT DISTINCT t1 AS CombinedValue FROM t1
    UNION ALL
    SELECT DISTINCT t2 FROM t2
    ) foo
GROUP BY
    CombinedValue
HAVING
    COUNT(*) = 1
相关问题