如何基于另一个表的值在SQL表上创建列

时间:2017-11-14 20:01:56

标签: sql sqlite

我目前有2个SQL表:table1table2table1有两列名为id_acolumn_atable2有两列名为id_bcolumn_b

我想在new_column中创建一个table1。如果new_column中存在table1.id_a的值,则table2.id_b的值应为1。否则,new_column的值应为0.

我该怎么做?我使用的是SQLite3,table1明显大于table2

3 个答案:

答案 0 :(得分:1)

一个简单的exists怎么样?

select t1.*,
       (case when exists (select 1 from table2 t2 where t2.id_b = t1.id_a)
             then 1 else 0
        end) as flag
from table1 t1

答案 1 :(得分:1)

有趣的select t1.*, case when t2.id_b is null then 0 else 1 end as new_column from table1 t1 left join table2 t2 on t2.id_b = t1.id_a 解决方案!在某些情况下,甚至可能比相关子查询更有效。

var grade = ["GradeA", "GradeB", "GradeC"];
var number = ["25","36","32"];
var obj = {};

grade.forEach(function(x, i){
    obj[x] = number[i];
});

console.log(JSON.stringify(obj));

答案 2 :(得分:1)

一个简单的IN怎么样?

SELECT *,
       id_a IN (SELECT id_b FROM table2) AS flag
FROM table1;