[英]Merge two queries and return one of the possible values
select value1 as value from T1 where id=10;
if id
does not exist in T1
- execute another query: 如果id
在T1
中不存在-执行另一个查询:
select value2 as value from T2 where id=10;
So, I want to join these queries and return a single value ( value1
or value2
). 因此,我想加入这些查询并返回一个值( value1
或value2
)。 Is it possible? 可能吗?
SOLUTION: 解:
My solution: 我的解决方案
select ifnull(value1, value2) as value from T1 left join T2 using(id) where id=10;
you can join the query using union 您可以使用工会加入查询
select value1 as value from T1 where id=10
union
select value2 as value from T2 where id=10;
as a result you can get any one of the value or both 结果,您可以获得任何一个值或两者皆有
TRY (tested) TRY(已测试)
SELECT COALESCE(t1.value1, t2.value2) AS Value FROM t1
INNER JOIN t2 USING(id)
WHERE id=10
this will always check first the table t1 for id=10 , if there is no value then see table t2 for the same id 这将始终首先检查表t1的id = 10 ,如果没有值,请参见表t2以获得相同的id
The single result column that replaces two common columns is defined using the coalesce operation. 使用合并操作定义替换两个公共列的单个结果列。 That is, for two t1.a and t2.a the resulting single join column a is defined as a = COALESCE(t1.a, t2.a) 也就是说,对于两个t1.a和t2.a,将所得的单个联接列a定义为a = COALESCE(t1.a,t2.a)
You can join the two queries on the id
field and then use the COALESCE
function to combine the two resulting fields into the output. 您可以在id
字段上加入两个查询,然后使用COALESCE
函数将两个结果字段组合到输出中。
This assumes that you already have a list of IDs to join against, though. 不过,这假定您已经有一个ID列表要加入。 Otherwise you're stuck doing a union or full join to get such a list first. 否则,您将无法进行联合或完全联接才能首先获得此类列表。
你也可以用这个
select Distinct(s1.id) from sample1 as s1 inner join sample2 as s2;
use union
of both 使用两者的union
like below : 像下面这样:
select t1.id from table1 as t1 where id=10
union
select t2.id from table2 as t2 where id=10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.