mysql - Check if a cat and subCat exist in two different table using a single sql statement -


i have 2 tables...

#maincats catid | catname ---------------- 1     | furniture 2     | cutlery  #subcats subcatid | subcatname | catid | catname  ------------------------------------- 1     | tables        | 1     | furniture 2     | chairs        | 1     | furniture 3     | knives        | 2     | cutlery 

when adding items third table - items, need check if valid category , subcategory exist.

the way data comes in right now, this:

http://www.example.com/additem/?cat=1&sub=2&add=table_lamps 

and way it's done this. this stripped down example.

1st: select count(catid) hascat maincats catid=1 if(hascat == 1) {  select count(subcatid) hassubcat subcats subcatid=2 , catid=1; if(hassubcat == 1) {  //do adding table here  }else{  echo 'a subcategory not found'; }    }else{  echo 'a category not found'; }  

is there way check if cat , subcat exist in 1 single step rather of code.

this thing comes old site 1998.

if can accept of providing more generic error message category or subcategory not found, can skip first select. skip both select: assuming third table has foreign keys pointing catid , subcatid, can perform insert without check, catching exceptions understand whether cat or subcat missing.

if need distinguish 2 error cases, can perform second select before first one: if second select succeds don't need execute first one, if second select fails (no category) execute first 1 understand whether @ least main category exists. in way, assuming in cases categories exist, avoid 50% of queries. again, perform insert without check, catch exceptions , perform first select understand whether @ least main category exists. in way avoid queries can still distinguish 2 error cases.

of course i'm assuming goal reduce queries better efficiency, not remove line of code.


Comments

Popular posts from this blog

php - Why I am getting the Error "Commands out of sync; you can't run this command now" -

linux - Does gcc have any options to add version info in ELF binary file? -

java - Are there any classes that implement javax.persistence.Parameter<T>? -