Sql 一次获取行信息
我有两张桌子: T1 T2 例如,如果我想获取post 100的信息,我将使用正常的select*从t1,t2获取表1和表2的信息,其中t1.post\u id=t2.post\u id。。。我将得到两行:一行的subid1=1,subid2=1,文本为AAA,另一行的subid1=1,subid2=2,文本为BBB。但我只需要得到一行包含两个不同文本的内容,比如:Sql 一次获取行信息,sql,Sql,我有两张桌子: T1 T2 例如,如果我想获取post 100的信息,我将使用正常的select*从t1,t2获取表1和表2的信息,其中t1.post\u id=t2.post\u id。。。我将得到两行:一行的subid1=1,subid2=1,文本为AAA,另一行的subid1=1,subid2=2,文本为BBB。但我只需要得到一行包含两个不同文本的内容,比如: post_id text1 text2 100 AAA BBB 我尝试了左连接和子查询,但总是得到两行或一个查
post_id text1 text2
100 AAA BBB
我尝试了左连接和子查询,但总是得到两行或一个查询错误U\U
有人知道我该怎么处理吗
谢谢:)您所寻求的通常称为“交叉表”查询。SQL语言不是为动态列生成而设计的,因此大多数产品都没有提供让它动态生成所需列的功能。但是,您可以通过静态定义列来生成一个查询,该查询将返回所需的信息:
Select T2.post_id
, Min( Case When T2.subid2 = 1 Then T2.text End ) As text1
, Min( Case When T2.subid2 = 2 Then T2.text End ) As text2
From T2
Where T2.post_id = 100
Group By T2.post_id
我找到了另一个解决方案:对每种情况使用两个左连接
select * from t1
left join (select answertext as text1 from t2 where subid1=1 and subid2=1) D
on t1.postid=t2.postid
left join (select answertext as text2 from t2 where subid1=1 and subid2=2) D
on t1.postid=t2.postid
什么是rdbms,哪个版本?@Sam和并非所有非rdbms特定的答案表现相同。如果你想得到性能从一般到较差的普通答案,那就去做吧
Select T2.post_id
, Min( Case When T2.subid2 = 1 Then T2.text End ) As text1
, Min( Case When T2.subid2 = 2 Then T2.text End ) As text2
From T2
Where T2.post_id = 100
Group By T2.post_id
select * from t1
left join (select answertext as text1 from t2 where subid1=1 and subid2=1) D
on t1.postid=t2.postid
left join (select answertext as text2 from t2 where subid1=1 and subid2=2) D
on t1.postid=t2.postid