views:

54

answers:

2

I have a MySql db with innoDB tables. Very simplified this is how two tables are layed out:

Table A:

  • controlID(PK)
  • controlText

Table B:

  • controlOptionID(pk)
  • controlID(FK to table A)
  • controlOptionType
  • controlOptionValue

So many controlOptions(table B) can reference one control(giving that control multiple options). But for each option two rows are made in table B: one row with controlOptionType = "linkToCreator" and controlOptionValue = (an ID to the template it was made from*). And the other row type = "optionSelected" and value = "true"(or false).

  • = its a pretty complicated setup, but basically instead of set columns we are making dynamic ones by means of the type being what the column would have been called. So I couldnt link to the template with FK.

So now I need to select every control(which will have 2 controlOptions linking to it) where the one controlOptionValue value is true or false(depending on what i need) and the other controlOptionValue is an text ID that I specify.

What I think is the best way to do it is a

SELECT * FROM tableB WHERE controlOptionType = 'linkToCreator'

Then do a loop over that result set saying:

SELECT * FROM tableB WHERE tableB.controlID = (the controlID in this iterations row) AND tableB.controlValue = 'true'

But maybe thatls really inefficient, and either way I have no clue how to do that. It would be great if I could get a single query(i.e. not using stored procedures) that I specified templateID and true or false and it gave me a row result if it didn't find anything.

BTW this is for a search in our application with will need to go through TONS of rows so performance is paramount. And yes, I know the setup isnt the greatest...

Thanks :D

+4  A: 
Mchl
Ha! Awesome, thanks so much :DThree last things, is it possible to make it so it only returns the result if it finds both ctrl 1 and ctrl 2? At the moment it returns null for ctrl1 and/or ctrl2 instead of just removing that row.And, if I wanted to to do another join(to something tableA links to) do I just add it as usual to the last line?
Matt
1. Change left joins to to inner joins2. Yes
Mchl
A: 

Try this:

SELECT * 
FROM Table_A 
LEFT JOIN Table_B
ON Table_A.ControlID = Table_B.ControlID
WHERE Table_A.controlOptionType = 'linkToCreator
eiefai