mysql - 不在声明中

mysql - not in statement

table 1 
id  name    value activ
1    abc    5      1
2    def    6      1
3    ghi    10     0
4    jkl    15     1


table 2 
id   name   value  table1_id
1    abc    100     1
2    jkl    200     4

我想 return 来自 table 1 的所有记录,其中 active = 1 和来自 table 2 的记录,其中 table1_id 指的是 table 1 从而跳过 table 1 与 table 中的 table1_id 相匹配的记录 2..

输出必须是这样的

name  value 
 abc    100
 def     6
 jkl     200 

我试过这样的东西..

select   s.name,
         s.value  
from table1 as s 
where s.active =1 and 
      s.id NOT `IN (select d1.table1_id 
                    from table2 as d1 
                    where d1.table1_id = s.id) 
union 
select d.id,
     d.name,
     d.value 
from table2 as d`

它总是 returns table 2 的所有记录。我无法在 'where d.table1_id = s.id' 之类的语句末尾使用 where 条件。它说 s.id is unknown 。

SQL Fiddle Demo

SELECT T1.name, 
       COALESCE(T2.value, T1.value) as value
FROM Table1 as T1
LEFT JOIN Table2 as T2
       ON T1.id = T2.table1_id
WHERE T1.active = 1

输出

| name | value |
|------|-------|
|  abc |   100 |
|  jkl |   200 |
|  def |     6 |
SELECT a.name,
  NVL(b.value, a.value)
FROM table1 a
LEFT OUTER JOIN table2 b
ON a.id      =b.table1_id
WHERE a.activ=1;

您可以使用 COALESCE

SELECT table_1.name, COALESCE(table_2.value, table_1.value) as value
FROM table_1
LEFT JOIN table_2
   ON table_1.id = table_2.id
WHERE table_1.active = 1