SQL如何插入和左连接

时间:2018-04-23 10:05:46

标签: sql

name table a            
1.budy                  
2.rendy                
3.rona                  
4.sandi
5.susi

table b
1.budy
2.rendy
3.rona

我怎样才能在桌子上用sql显示表b b sandi和susi?

5 个答案:

答案 0 :(得分:2)

测试:http://rextester.com/HDZ43705

这将满足您的需求:

select * from A 
except 
select * from B

答案 1 :(得分:0)

您可以使用TableA中的LEFT JOINNOT EXISTS检查TableB中是否存在数据,TableB中不存在,然后插入INSERT INTO tableb(name) SELECT A.name FROM tableA A LEFT JOIN tableB B ON B.name = A.name WHERE B.name IS NULL

SELECT A.name 
FROM tableA A
WHERE NOT EXISTS(SELECT 1 FROM tableB B WHERE B.name = A.name)

SET @datetime = '2018-04-22';

SELECT date(datetime) as day
    ,(CASE WHEN
     (SELECT content FROM logs WHERE date(datetime) = @datetime ORDER BY datetime LIMIT 1)
        >
     (SELECT content FROM logs WHERE date(datetime) = @datetime ORDER BY datetime desc LIMIT 1)
       THEN min(content) - max(content)
       ELSE max(content) - min(content) END) as diffN
    FROM logs 

    WHERE Name = 'Foo' AND date(datetime) = @datetime
    GROUP BY day(datetime)
    ORDER BY datetime
    ;

答案 2 :(得分:0)

试一试: -

INSERT INTO tableb
SELECT tablea.id,tablea.name,tableb.id,tableb.name
 FROM tablea
   LEFT JOIN tableb
      ON tablea.name = tableb.name;

答案 3 :(得分:0)

可能不是最优化的解决方案,但猜猜它会起作用:

SELECT name 
FROM TableB

UNION

SELECT name 
FROM TableA

如果那是你要查找的(表的连接视图),将在两个表中返回数据的DISTINCT版本。

如果你只想在A中显示不在B中的名字,那么就像这样:

SELECT name FROM TableA WHERE name NOT IN (SELECT name FROM TableB)

我认为这与DEEPAK提出的基本相同,只是他更紧凑和现代。

答案 4 :(得分:0)

使用此

INSERT INTO tableb

SELECT tablea.id,tablea.name FROM dbo.tablea

LEFT JOIN dbo.tableb

ON tablea.id = tableb.id

WHERE tableb.id为null