一对多sql联合查询:

2025-01-07 08:11:19
推荐回答(5个)
回答1:

select t1.id,t1.name,min(t2.type) from t1 left join t2 on t1.id=t2.pid group by t1.id,t1.name
不知道你要取的单条是靠哪个条件选择的,暂时取最小

回答2:

SELECT t1.id, t1.name, t2.type
FROM T1 LEFT OUTER JOIN T2 ON T1.ID = T2.ID AND T2.pid = '1'

要是只显示T2中pid的奇数时
SELECT t1.id, t1.name, t2.type
FROM T1 LEFT OUTER JOIN T2 ON T1.ID = T2.ID AND T2.pid%2 = 1

这时可以得出你想要的结果.
不知你想要的是不是这样的编辑.

希望能给你点帮助...

回答3:

不能用join,join 有重复数据。

select t1.*,
(select top 1 t2.type from t2 where t2.pid = t1.id order by t2.id) as type
from t1

有问题hi我。

回答4:

select t1.id,t1.name, (case when isnull(temp_t2.type) then '' else temp_t2.type end) as type
from t1
left join (select pid, type from t2 group by pid) as temp_t2
on t1.id=temp_t2.pid;

//select pid, type from t2 group by pid 这里去掉重复的pid,每个pid留下单条数据 然后可以left join 了

回答5:

select t1.id,t1.name,t2.type
from t1 left join (t2 inner join (select id,count(pid) as count_pid from t2 group by id) t_count on t2.id = t_count.id and t_count.count_pid > 1 ) t_count on t1.id = t_count.id