我有两张桌子:一张是album,另一张是album_photo。我需要展示的相册,其中至少有一张批准的照片。我有以下表格的字段:
album
Id name date
1 myalbums 1-1-10
2 youralbum 2-3-10
3 somealbum 3-4-10
album_photo
id album_id photo_url status
1 2 /some/url Pending
2 1 /some/url Approved
3 1 /some/url Approved
3 3 /some/url Declined在上表中,只有id 1的相册(“我的相册”)已批准照片,其他两张相册没有任何已批准的照片。所以我想要一个查询,它显示至少有一张经过批准的照片的相册的名称。
我试过这样做:
select a.*, a.id as album_id, ap.*
from album a, album_photo ap
where a.id = ap.album_id
and (select count(*) from album_photo where ap.status = 'Approved') > 0;发布于 2015-05-08 11:34:30
您的查询略有错误,尽管在开始时加入了它们,只需在where子句中加入它们。
select a.*,a.id as album_id from album a
where (select distinct ap.album_id from album_photo ap where
ap.album_id=a.id and ap.status='Approved')>0;休息一下你所做的一切都是正确的。另一种解决方案是没有区别的,因为我们知道in总是唯一的,所以内部查询中的不同可以删除,并且可以按下面的方式编写。
select a.*,a.id as album_id from album a
where (select count(*) from album_photo ap where
ap.album_id=a.id and ap.status='Approved')>0;发布于 2015-05-08 11:34:19
以下查询应返回至少有一张照片已被批准的相册(ant其所有照片是否已被批准)。
select a.*,a.id as album_id,ap.*
from (select a1.* from album a1 where a1.id in (select distinct ap1.album_id from album_photo ap1 where ap1.status='Approved')) a, album_photo ap
where a.id=ap.album_id;如果你只想要没有照片的相册,你可以使用
select a1.* from album a1 where a1.id in (select distinct ap1.album_id from album_photo ap1 where ap1.status='Approved')发布于 2015-05-08 11:54:16
SELECT *
FROM album a
WHERE EXISTS (
SELECT 1
FROM album_photo ap
WHERE ap.album_id = a.id AND ap.status = 'Approved'
);存在产生的半连接,可以期望比连接执行更好。
https://stackoverflow.com/questions/30122563
复制相似问题