Jump to content

Select query Where clause from another table


mrt003003

Recommended Posts

Hi there,

 

I was wonderin if its possible to create a select query from one table thats Where clause is determinded from another table. For example my 2 tables are: Structures and Planetstructures. Structures holds the structure details and Planetstructures holds the planet details and the structure detals etc.. When there are 3 of any planetstructure records of the same type, i want to select the data in the structures table leaving out the structure that coresponds to the planetstructure with more than 3 records of the same type.

 

SELECT s.StructureName, s.Maintenance, g.PlanetStructureID, g.ConstructionTime, g.PlanetID FROM structures s
LEFT JOIN planetstructures g ON (s.StructureID = g.StructureID)
WHERE p.PlanetID = %s[b] AND Totalrows of any one type < 3

 

I hope ive made sense. Any ideas on how i can achieve this please??

 

Thanks :)

I don't know about what you said, but at least the SQL makes sense to me.

 

You can use an IN or, probably more appropriately, a NOT IN condition and subquery.

...AND s.StructureID NOT IN (SELECT StructureID FROM planetstructures GROUP BY StructureID,  HAVING COUNT() >= 3)

 

It can be simpler than that if all planetstructures which belong to the same structure and have the same type also have the same ConstructionTime and PlanetID: just move the GROUP BY and HAVING into the main query and forget the NOT IN condition and subquery.

Couldn't you just do:

 

 

SELECT COUNT(<type>) AS TotalRows, s.StructureName, s.Maintenance, g.PlanetStructureID, g.ConstructionTime, g.PlanetID FROM structures s
LEFT JOIN planetstructures g USING (StructureID)
WHERE p.PlanetID = %s GROUP BY <type> HAVING TotalRows < 3

 

 

:confused:

 

//EDIT: Used PHP instead of code lol

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.