douliedai4838 2018-11-15 10:34
浏览 187

如何使用循环编写动态sql查询

please check the image. enter image description here

I'm trying to write a query to fetch the data from the database, but am not getting. I want to fetch the title of ConstituencyId 3. For 3rd constituency, I have to display 4 different titles. if a user selects constituency 2 and 3 I have to display titles of 2nd and 3rd Constituency.

SELECT N1.Id, N1.Title From NewsContent N1
Where N1.Id > 0 and  
(N1.ConstituencyId like ('%2%') OR N1.ConstituencyId Like ('%3') OR N1.ConstituencyId like ('%4%'));

This is the equery I have to write dynamically because I don't know what the user selects. am not getting in dynamically. Please help me out on this.

Thanks

  • 写回答

1条回答 默认 最新

  • dtf579777 2018-11-15 10:37
    关注

    You may use FIND_IN_SET here, e.g.

    SELECT N1.Id, N1.Title
    FROM NewsContent N1
    WHERE
        N1.Id > 0 AND
        FIND_IN_SET('2', N1.ConstituencyId) > 0 AND
        FIND_IN_SET('3', N1.ConstituencyId) > 0;
    

    But note that storing CSV in the ConstituencyId column means that your table is not completely normalized. This is not ideal, for the above reason that it makes querying difficult, and updating even more difficult. Fortunately, MySQL has a FIND_IN_SET function which can help, but we should avoid relying on it.

    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀