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 :)

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.