dongtan7418 2016-07-19 13:35
浏览 35
已采纳

比较表字段值以在数据库中插入新值

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.

  • 写回答

1条回答 默认 最新

  • drus40229 2016-07-19 13:50
    关注
    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 vc6.0中想运行代码的时候总是提示无法打开文件是怎么回事
  • ¥25 关于##爬虫##的问题,如何解决?:
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题