开发者

How to retrieve the not common values from 2 tables?

I have the 2 following tables t1, t2 with values,

t1        t2
1         4
2         2
3         3

Now I want to output

开发者_如何学运维1 
4

How can I get this output in select query ?


This will get you each item from t1 that is not present in t2, and each item in t2 that is not present in t1:

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

(I have assumed that the field name in each table is named id just for the sake of being able to write a query against the tables.)

Another way would be:

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


Another way. Just COUNT them.

This works if the values are unique per table

SELECT
    CombinedValue
FROM
    (
    SELECT t1 AS CombinedValue FROM t1
    UNION ALL
    SELECT t2 FROM t2
    ) foo
GROUP BY
    CombinedValue
HAVING
    COUNT(*) = 1

If not unique per table

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


you can use Joins in MySql to proceed and to obtain result.

this will help you http://www.techrepublic.com/article/sql-basics-query-multiple-tables/1050307

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜