我已经搜索了我的问题,但我找不到合适的东西。 什么方法可以带来最终结果?
初始职位:(使用数据库:DB2)
使用UNION
查询,例如:
SELECT 'HEAD', state, ID, Name, Country, '0'
FROM TABLE_A
WHERE state= '1'
UNION
SELECT 'POS', state, '0', '0', '0', Item
FROM TABLE_B
WHERE state= '1'
结果:
+------+-------+-----+------+---------+------+ | TYPE | STATE | ID | Name | Country | Item | +------+-------+-----+------+---------+------+ | HEAD | 1 | 999 | Test | PL | 0 | +------+-------+-----+------+---------+------+ | POS | 1 | 0 | 0 | 0 | ABC | +------+-------+-----+------+---------+------+ | POS | 1 | 0 | 0 | 0 | DEF | +------+-------+-----+------+---------+------+ | POS | 1 | 0 | 0 | 0 | GHI | +------+-------+-----+------+---------+------+
所以"州=' 1'"是固定的
我想根据预查询给出的结果选择动态选择动态:
查询:
SELECT state
FROM TABLE_C
结果:
+-------+ | state | +-------+ | 1 | +-------+ | 2 | +-------+ | 3 | +-------+
最终结果应为:
+------+-------+-----+------+---------+------+ | TYPE | STATE | ID | Name | Country | Item | +------+-------+-----+------+---------+------+ | HEAD | 1 | 999 | Test | PL | 0 | +------+-------+-----+------+---------+------+ | POS | 1 | 0 | 0 | 0 | ABC | +------+-------+-----+------+---------+------+ | POS | 1 | 0 | 0 | 0 | DEF | +------+-------+-----+------+---------+------+ | POS | 1 | 0 | 0 | 0 | GHI | +------+-------+-----+------+---------+------+ | HEAD | 2 | 888 | Test2| DE | 0 | +------+-------+-----+------+---------+------+ | POS | 2 | 0 | 0 | 0 | XXX | +------+-------+-----+------+---------+------+ | POS | 2 | 0 | 0 | 0 | YYY | +------+-------+-----+------+---------+------+ | POS | 2 | 0 | 0 | 0 | GGG | +------+-------+-----+------+---------+------+ | HEAD | 3 | 555 | Test7| DE | 0 | +------+-------+-----+------+---------+------+ | POS | 3 | 0 | 0 | 0 | TTT | +------+-------+-----+------+---------+------+ | POS | 3 | 0 | 0 | 0 | SSS | +------+-------+-----+------+---------+------+ | POS | 3 | 0 | 0 | 0 | AAA | +------+-------+-----+------+---------+------+
答案 0 :(得分:1)
虽然你的问题不是很清楚你究竟想要什么......希望这就是你所需要的......
SELECT 'HEAD', state, ID, Name, Country, '0'
FROM TABLE_A
WHERE state in (SELECT state FROM TABLE_C)
UNION
SELECT 'POS', state, '0', '0', '0', Item
FROM TABLE_B
WHERE state in (SELECT state FROM TABLE_C)