SashaBuilder3
Programmer
Hello dear SQL experts,
I am working on a project related to arthropod species identification.
Here is a simplified table where we list various arthropod species with their properties:
i_spID and t_property comprise the primary key.
Each species may have multiple properties (unlimited number) in the table. The ultimate goal is giving a set of properties to identify (ideally) a single species.
I have come up with a query having multiple subqueries, each for each pair of property/value:
(this one identifies the cocroach 'Blatta germanica')
The problem is that as the number of properties grows the query becomes too combersome especially the "where" part in which we need to connect each subquery with all the others through i_spID.
So is there a better way to write the query?
-- create and fill in table SQL:
I am working on a project related to arthropod species identification.
Here is a simplified table where we list various arthropod species with their properties:
i_spID | t_property | t_species | i_property_val |
---|---|---|---|
1 | nmb_legs | Blatta germanica | 6 |
1 | nmb_wings | Blatta germanica | 4 |
2 | nmb_legs | Musca domestica | 6 |
2 | nmb_wings | Musca domestica | 2 |
3 | nmb_legs | Latrodectus hesperus | 8 |
i_spID and t_property comprise the primary key.
Each species may have multiple properties (unlimited number) in the table. The ultimate goal is giving a set of properties to identify (ideally) a single species.
I have come up with a query having multiple subqueries, each for each pair of property/value:
SQL:
SELECT t1.i_spID,t1.t_species
FROM (SELECT * FROM DBO.t_species WHERE t_property='nmb_legs' AND i_property_val=6) AS t1,
(SELECT * FROM DBO.t_species WHERE t_property='nmb_wings' AND i_property_val=4) AS t2
WHERE t1.i_spID=t2.i_spID
The problem is that as the number of properties grows the query becomes too combersome especially the "where" part in which we need to connect each subquery with all the others through i_spID.
So is there a better way to write the query?
-- create and fill in table SQL:
SQL:
CREATE table DBO.t_species
(
i_spID int NOT NULL,
t_property nvarchar(20) NOT NULL,
t_species nvarchar(50),
i_property_val int
);
ALTER TABLE DBO.t_species
ADD CONSTRAINT pkID_sp01 PRIMARY KEY (i_spID,t_property);
INSERT INTO DBO.t_species (i_spID, t_property, t_species, i_property_val)
VALUES (1, 'nmb_legs', 'Blatta germanica', 6),
(2, 'nmb_legs', 'Musca domestica', 6),
(3, 'nmb_legs', 'Latrodectus hesperus', 8),
(1, 'nmb_wings', 'Blatta germanica', 4),
(2, 'nmb_wings', 'Musca domestica', 2)
;