mysql join,来自一个表的所有行和来自另一个表的第一行

时间:2012-08-15 06:48:55

标签: mysql mysqli

我有两个表属性和property_images

where properties.pid = property_images.pid

一个属性可以有多个图像,我必须选择所有属性和第一个属性图像

4 个答案:

答案 0 :(得分:2)

select 
    t1.* ,
    t2.image
from properties as t1 
left join (
           select 
               min(id), 
               pid, 
               image 
           from property_images  
           group by pid) as t2 
on t2.pid = t1.pid

答案 1 :(得分:0)

select * from property a 
left join ( select * from property_Images b group by pid) s on s.pid=a.pid ;

答案 2 :(得分:0)

select 
    pro.* 
from properties as pro 
left join (
           select 
               min(id),
               pid,
               image 
           from property_images  
           group by pid) as pro_img 
on pro.pid = pro_img.pid

答案 3 :(得分:0)

select *  
from properties as t1 
left join property_images t2 on (t1.pid=t2.pid) 
where t2.id in
           (select min(id) from property_images where property_images.pid=t2.pid)

OR 假设property_images中有唯一的密钥ID:

select *  
from properties as t1 
left join (select min(id) minID, pid from property_images group by pid) t2
   on (t1.pid=t2.pid)  
left join property_images t3 on (t2.minID=t3.id) 

选择数据库中哪一个更快。