2015-10-22 27 views
0

这里的新手到SQL。所以我有两张桌子,比如下面的两张桌子。如何根据几个条件查询SELECT和Concat()列值?

表A

set_num s_id s_val 
100  3  AA 
100  5  BB 
200  3  AA 
200  9  CC 

表B

s_id s_val phrase  seq 
1  DD  'hi'   'first' 
3  AA  'hello'  'first' 
6  EE  'goodnight' 'first' 
5  BB  'world'  'second' 
9  CC  'there'  'second' 
4  FF  'bye'  'first' 

我想在两列连接表A和表B,就像一个复合键(S_ID,S_VAL),我想返回 set_num来自表A以及表B中的短语的连接(我们将称其为entire_phrase,concat(...)AS entire_phrase)。 串联还应遵循短语串联的顺序。这将由表B中的seq列确定每个短语。 “第一”将表明这个短语需要先来和“第二”,接下来会好。我想用SELECT查询来做到这一点,但不确定这是否可能,而不会变得复杂。我可以在SELECT中执行此操作还是需要另一种方法?

预期输出:

set_num entire_phrase 
100  'hello world' 
200  'hello there' 

而且不

set_num entire_phrase 
100  'world hello' 
200  'there hello' 

任何帮助/办法将不胜感激!

+0

你保证有整整两个记录每'set_num'一个标记为“第一”,另一个为“第二“在表A中? –

+0

你真的需要它3种不同的RDBMS吗? –

+0

在mysql中,使用group_concat()很容易。 – Shadow

回答

1

你可以这样说:

select temp1.set_num, concat(phrase1,' ',phrase2) as entire_phrase 
from (
(
select set_num, b.phrase as phrase1 
from TableA as A 
join TableB as B 
on a.s_id = b.s_id 
and a.s_val = b.s_val 
and b.seq = 'first' 
) as temp1 
join 
(
select set_num, b.phrase as phrase2 
from TableA as A 
join TableB as B 
on a.s_id = b.s_id 
and a.s_val = b.s_val 
and b.seq = 'second' 
) as temp2 
on temp1.set_num = temp2.set_num 
) 

运行位置:http://sqlfiddle.com/#!9/d63ac3/1

+0

谢谢你。我会试一试,让你知道。 Qq ...如果每组可以有不同数量的短语,那么只需要增加连接数? – tony

+0

是的,假设都是强制性的。另外,如果还有更多,将有更好的方法来解决它。我只是在这里“相当简单地理解”。 – Turophile