Mysql连接两个表根据条件得到相同的字段值

时间:2016-01-20 07:39:49

标签: mysql sql

我有这样的拖鞋

表a

id  email    firstname  lastname
1   a@a.com   xx         xx      
2   b@b.com   xb         ab      

表b

  id     email    firstname   lastname
  1      a@a.com    sd          cx       
  2      c@c.com    df          dr        

我想要这样

  email      firstname     lastname

   a@a.com       xx         xx
   b@b.com       xb         ab
   c@c.com       df         dr

任何人请帮助我。我试过工会,明显没有得到我的结果

3 个答案:

答案 0 :(得分:0)

你可以试试这个: -

SELECT email, firstname, lastname
FROM table_a
UNION
SELECT email, firstname, lastname
FROM table_b
WHERE email NOT IN (SELECT email FROM  table_a)

答案 1 :(得分:0)

你可以做到

select email, firstname, lastname from a
union all
select email, firstname, lastname from b
where email not in (select email from a)

答案 2 :(得分:0)

SELECT email
     , firstname
     , lastname 
  FROM table_a
 UNION
SELECT b.email
     , b.firstname
     , b.lastname 
  FROM table_b b 
  LEFT 
  JOIN table_a a 
    ON a.email = b.email 
 WHERE a.email IS NULL;