Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/image-processing/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用联接的静态和动态表的sql查询_Sql - Fatal编程技术网

使用联接的静态和动态表的sql查询

使用联接的静态和动态表的sql查询,sql,Sql,我正试图为下表编写一个查询 表A包含动态数据-ID、类别和类型 +-----+----------+---------------+ | id | category | type | +-----+----------+---------------+ | 1 | ETD | H49A | | 2 | ETD | SZ8A | | 3 | ETD | VQA5 | | 4 |

我正试图为下表编写一个查询

表A包含动态数据-ID、类别和类型

+-----+----------+---------------+
| id  | category  | type         |
+-----+----------+---------------+
|   1 |      ETD | H49A          |
|   2 |      ETD | SZ8A          |
|   3 |      ETD | VQA5          |
|   4 |      ETD | Null          |
|   5 |      ETD |   NA          |
|   6 |      ETD |               |
|   - |        - |   -           |
|   - |        - |   -           |
|  16 |      OTC | BVX9A         |
|  17 |      OTC | KG4G          |
+-----+----------+---------------+
静态表B包含类别和类型组合到属性的映射:

+-----+----------+---------------+
| atr | category  | type         |
+-----+----------+---------------+
|   V |      ETD | H49A          |
|   W |      ETD | SZ8A          |
|   X |      ETD | NA            |
|   Y |      OTC | BVX9A         |
|   Z |      OTC | NA            |
|   - |       -  |   -           |
+-----+----------+---------------+
表a中的所有类别均为表b中的类别

结果应该是这样的。查询应该是通用的,并且取决于表a中的特定值

+-----+----------+
| id  |      atr | 
+-----+----------+
|   1 |       V  |
|   2 |       W  |
|   3 |       X  |
|   4 |       X  |
|   5 |       X  | 
|   6 |       X  |
|   - |        - | 
|   - |        - | 
|  16 |       Y  |
|  17 |       Z  |
+-----+----------+

我想您需要两个
join
s,一个引入匹配值(如果有),另一个引入默认值:

select a.id, coalesce(b.atr, bdef.atr)
from a left join
     b
     on a.category = b.category and
        a.type = b.type left join
     b bdef
     on a.category = b.category and b.type = 'NA'

好啊您尝试了什么?我尝试了左联接,能够获得匹配的记录,但无法获得类别不匹配的值。下面是给出匹配记录的查询,在A.cat=B.cat和A.type=B.type ORDER BY A.id上从左连接B中选择A.id、B.atr;