Insert data from one table to another table where two columns do not match

时间:2015-09-01 22:24:30

标签: mysql database

I have two tables.

TABLE A
ID | LABEL|PARENT_ID| VISIBLE | HIDEABLE
1  |SPORTS|   1     |    1    |    1
2  | FOOD |   1     |    1    |    0
3  | CARS |   1     |    0    |    1
4  |TRAVEL|   1     |    1    |    1
5  | LOVE |   1     |    1    |    1
6  | OTHER|   1     |    1    |    0
7  | SHOES|   3     |    0    |    1
8  |TRAVEL|   3     |    1    |    1
9  |NATURE|   3     |    1    |    1
10 |FRIEND|   3     |    1    |    0
11 | CARS |   3     |    0    |    1
12 | LOVE |   3     |    1    |    1

TABLE B
ID | LABEL|PARENT_ID| DISPLAY_POST | DISPLAY_COMMENTS
1  |SPORTS|   1     |         1    |    1
2  | FOOD |   1     |         1    |    0
3  | CARS |   1     |         0    |    1
4  |TRAVEL|   3     |         1    |    1

I want to insert data into TABLE B from TABLE A with these checks:

A.LABEL <> B.LABEL AND A.VISIBLE=1 AND A.HIDEABLE=1

How can I do this?

Everything I try it returns duplicates or missing rows.

1 个答案:

答案 0 :(得分:0)

Just use insert . . . select with the right conditions:

insert into b( . . .)
     select . . .
     from a
     where a.visible = 1 and a.hideable = 1 and
           not exists (select 1 from b2 where a.label = b2.label);

The . . . are just the list of columns for inserting.