Search code examples
mysqldatabase-designloopsentity-attribute-value

Loop in MySql, or alternative?


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


Solution

  • Like this?

    SELECT * FROM tableA AS A
    LEFT JOIN tableB AS ctrl1 ON (A.controlID = ctrl1.controlID AND ctrl1.controlOptionType = ? AND ctrl1.controlOptionValue = ?)
    LEFT JOIN tableB AS ctrl2 ON (A.controlID = ctrl2.controlID AND ctrl2.controlOptionType = ? AND ctrl2.controlOptionValue = ?)