mysql - 不在声明中

标签 mysql sql notin

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

我想返回表 1 中 active = 1 的所有记录以及表 2 中的记录,其中 table1_id 引用表 1 的 id,从而跳过表 1 中与表 2 中的 table1_id 匹配的记录。

输出必须是这样的

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`

它总是返回表 2 的所有记录。我无法在语句末尾使用 where 条件,例如 'where d.table1_id = s.id' 。它说 s.id 未知。

最佳答案

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 |

关于mysql - 不在声明中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36043539/

相关文章:

php - 如何在 PHP 中的其他 while 循环中运行 while 循环?

mysql - 如何在层次结构中显示,,

sql - 在需要条件的上下文中指定的非 bool 类型表达式,位于 'END' 附近

php - 来自mysql中多个表的不同值

sql - 使用 NOT IN 子句的 Hive 查询的替代方案

mysql - 子查询优化

php - 在sql中从一个表到另一个表的数据替换期间如何处理空值?

mysql - 使用 mySQL 命令删除自定义帖子类型数据

mysql - SQL:这个 "where if"查询有什么问题?

sql-server - 当有 NULL 值的结果时 NOT IN 子查询失败