我的数据库中有两个表:AppropriateFor
和AquariumModel
,如下所示。它们共享三个键 - AquariumType,Salinity和Volume。我试图找到适合多种物种的所有水族馆模型。我试图正确计算AppropriateFor
中的主要元组,然后将其与AquariumModel
表连接起来。
AppropriateFor表有四列:speciesName,aquariumType,salinity,volume:
RED-BELLIED PACU AGGRESSIVE FRESHWATER 300
GOLDEN MORAY EEL AGGRESSIVE MARINE 25000
NURSE SHARK AGGRESSIVE MARINE 25000
COMMON TOADFISH COMMUNITY BRACKISH 150
DRAGON GOBY COMMUNITY BRACKISH 150
BRONZE CORYDORAS COMMUNITY FRESHWATER 250
COMMON DISCUS COMMUNITY FRESHWATER 250
SPOTTED RAPHAEL COMMUNITY FRESHWATER 250
UPSIDE-DOWN CATFISH COMMUNITY FRESHWATER 250
BLUESPOTTED ANGELFISH COMMUNITY MARINE 50000
CHALK BASS COMMUNITY MARINE 50000
FLAME ANGELFISH COMMUNITY MARINE 50000
ORIENTAL SWEETLIPS COMMUNITY MARINE 50000
ROUND STINGRAY COMMUNITY MARINE 50000
ROYAL ANGELFISH COMMUNITY MARINE 50000
TEIRA BATFISH COMMUNITY MARINE 50000
BARTLETTS ANTHIAS REEF MARINE 75000
BELLUS ANGELFISH REEF MARINE 75000
CHALK BASS REEF MARINE 75000
COPPERBANDED BUTTERFLYFISH REEF MARINE 75000
MANDARINFISH REEF MARINE 75000
COMMON TOADFISH SPECIES BRACKISH 100
GREEN SPOTTED PUFFER SPECIES BRACKISH 100
REEDFISH SPECIES BRACKISH 100
ELECTRIC EEL SPECIES FRESHWATER 500
ORNATE BICHIR SPECIES FRESHWATER 500
REEDFISH SPECIES FRESHWATER 500
BRAZILIAN SEAHORSE SPECIES MARINE 10000
AquariumModel也有四列:aquariumType,salinity,volume,price:
AGGRESSIVE BRACKISH 125 200
AGGRESSIVE FRESHWATER 300 500
AGGRESSIVE MARINE 25000 4500
COMMUNITY BRACKISH 150 250
COMMUNITY FRESHWATER 250 400
COMMUNITY MARINE 50000 7000
REEF MARINE 75000 10000
SPECIES BRACKISH 100 150
SPECIES FRESHWATER 500 800
SPECIES MARINE 10000 3000
答案 0 :(得分:3)
我认为你可以从两个表一起加入你需要的值,这将从这样开始:
SELECT *
FROM aquariummodel am
JOIN appropriatefor af ON am.aquariumtype = af.aquariumtype AND am.salinity = af.salinity AND am.volume = af.volume;
然后,您想要按水族箱类型中的所有值进行分组,并使用计数大于1的条件。所以我会将查询更改为:
SELECT am.*, COUNT(*) AS numFishAppropriateFor
FROM aquariummodel am
JOIN appropriatefor af ON am.aquariumtype = af.aquariumtype AND am.salinity = af.salinity AND am.volume = af.volume
GROUP BY am.aquariumtype, am.salinity, am.volume
HAVING COUNT(*) > 1;
修改强> 这是一个SQL Fiddle来证明它有效。
如果可以的话,我想评论一下你的数据库的设计。
在适当的表中,您有几个从水族模型表重复的列。我会在你的aquariummodel表中添加一个主键(比如auto_increment id),并在适当的表中使用该id。这样,aquariummodel将有5列,但适合可以减少到两列:speciesname
和aquariummodel_id
。只是一个建议。