I inherited a website with an existing database structure. I have one table (TABLE1
) that has something like the following structure:
POSITION_1_TAGS_PERMITTED | POSITION_2_TAGS_PERMITTED | POSITION_3_TAGS_PERMITTED
----------------------------------------------------------------------------------
CD | EN,CS | TECH,CS
TABLE1
has this structure up to 20 columns.
I then have another table (TABLE2
) that stores the selected value (also has 20 columns):
POS1_SEL_SYMBOL | POS2_SEL_SYMBOL | POS3_SEL_SYMBOL | POS4_SEL_SYMBOL
---------------------------------------------------------------------
A | AAPL | | AA
I have the tags for the selected variable in this case the tag for my variable is CS
. I'd like to find the position in TABLE1
that has the allowed tags and then look in TABLE2
to see if that position already has an entry in it. In this case it would identify position 3 as the column to add my entry to and then I would write a new update statement to add that entry to the database. Is there an easy way to do this with the column format of my database?
EDIT: If there are multiple tags for the variable I'd like it to search the permitted tags column for any value in it. I tried to update my SQL statement to be something like the following:
SELECT eventid,
CASE
WHEN (FIND_IN_SET("S&P", POSITION_1_TAGS_PERMITTED) OR FIND_IN_SET("CS", POSITION_1_TAGS_PERMITTED)) AND POS1_SEL_SYMBOL = ""
THEN 1
END AS found_col
FROM TABLE1
JOIN TABLE2
USING (eventid)
WHERE EVENTID='159'
This query doesn't give me the same results as just searching for CS did.
SELECT eventid,
CASE
WHEN FIND_IN_SET('CS', POSITION_1_TAGS_PERMITTED) AND POS1_SEL_SYMBOL = ''
THEN 1
WHEN FIND_IN_SET('CS', POSITION_2_TAGS_PERMITTED) AND POS2_SEL_SYMBOL = ''
THEN 2
WHEN FIND_IN_SET('CS', POSITION_3_TAGS_PERMITTED) AND POS3_SEL_SYMBOL = ''
THEN 3
...
WHEN FIND_IN_SET('CS', POSITION_20_TAGS_PERMITTED) AND POS20_SEL_SYMBOL = ''
THEN 20
END AS found_col
FROM TABLE1
JOIN TABLE2 USING (eventid)
See SQL Insert in first empty column in a row MySQL error for an UPDATE
query that you could adapt using the above structure so that you update the field that's found rather than just returning the column number. But with 20 columns, that query will get really long.