用户有宠物,宠物可能有图片一张图片可能被设为主图片(mainpic = 0或mainpic = 1)
我需要从宠物表中获取所有宠物数据,我还需要主屏幕= 1或第一张图片的图片ID,如果图片表中没有图片,则需要null。我需要获取宠物数据,即使它根本没有图片。
目前我使用2个查询来完成此操作: SELECT * FROM pets WHERE pets.userId ='$ userId'ORDDER BY pets.created ASC LIMIT 5 ... 对于每个结果:SELECT id FROM pictures WHERE petId ='$ petId'ORDER BY mainpic DESC LIMIT 1
我需要在一个查询中进行优化。
谢谢, 哈姆雷特
答案 0 :(得分:1)
使用内部联接来省略不匹配的记录
select *
from pets inner join pictures
on pets.id = petId and mainpic=1
where userId=?
order by pets.created ASC limit 5
如果您只想在图片相关字段中使用null但想要宠物信息(您的Q有点不清楚)那么请使用左连接
select *
from pets left join pictures
on pets.id = petId and mainpic=1
where userId=?
order by pets.created ASC limit 5
答案 1 :(得分:0)
试试这个:
SELECT * FROM pets
INNER JOIN pictures ON pictures.petid = pets.id AND pictures.mainpic = 1
WHERE pets.userid='$userid'
答案 2 :(得分:0)
SELECT *
FROM pets p
LEFT OUTER JOIN (
SELECT *
FROM pictures pict
WHERE pict.mainpic = 1
) pict ON pict.petid = p.petid
WHERE p.userid = '$userid'
答案 3 :(得分:0)
SELECT (
SELECT id
FROM pictures pi
WHERE pi.petid = pe.petid
ORDER BY
mainpic DESC
LIMIT 1
)
FROM pets pe