電子書籍の厳選無料作品が豊富!

テーブルA
ユーザーID,地名,県名,評価
テーブルB
ユーザーID,県名,制覇flag

のような二つのテーブルがあると仮定してSelect文1、
"select 県名,count(地名) from テーブルA where ユーザーID=1 group by 県名 order by count(地名);"
の結果が

県名,count(地名)
北海道,30
東京,22
京都,15
名古屋,10
鳥取,9
沖縄,8

であるとし、
Select文2、
"select 県名 from テーブルB where usrid=1 and 制覇flag='true'"
の結果が、

県名
北海道
東京

とします。
このSelect文1の結果から、Select文2の結果を引いて

県名,count(地名)
京都,15
名古屋,10
鳥取,9
沖縄,8

の結果を得るにはどうすればよいでしょうか?
Mysqlのバージョンは5.0.21です。

A 回答 (1件)

名古屋は、県名ではないですが?



-- example 1
select 県名,count(地名) as cnt
from tblA
where uid=1
and 県名 not in(
select 県名
from tblB
where tblA.uid=uid
and 制覇flag=1)
group by 県名
order by cnt desc;

-- example 2
select 県名,count(地名) as cnt
from tblA
where uid=1
and not exists
(select * from tblB
where tblA.県名=県名
and tblA.uid=tblB.uid
and 制覇flag=1)
group by 県名
order by cnt desc;

-- example 3
select tblA.県名,count(地名) as cnt
from tblA
left join tblB
on tblA.県名=tblB.県名
and tblA.uid=tblB.uid
and 制覇flag=1
where tblA.uid=1
and tblB.県名 is null
group by tblA.県名
order by cnt desc
;

-- example 3
select tblA.県名,count(地名) as cnt
from tblA
left join tblB
on tblA.県名=tblB.県名
and tblA.uid=tblB.uid
and 制覇flag=1
where tblA.uid=1
and tblB.県名 is null
group by tblA.県名
order by cnt desc
;
    • good
    • 0
この回答へのお礼

>名古屋は、県名ではないですが?
そうでした!

クエリ無事成功しました。どうもありがとうございます。

お礼日時:2007/07/14 08:59

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!