mysql过滤器,基于用户输入的MySQL过滤器查询

My previous question was not giving a clear idea about my problem, that is why I am asking a new question .

Here is my table structure

id,

subject (varchar),

category(varchar),

medium(json),

material(json),

style(json)

User can able to search based on the values in table fields ie if user choose only subject (he can select it from multiple select dropdown) query result contains rows that matches the selected items.

If user selected subject and category query result contains rows that matches the selected items and so on (in short it's a filter search like shopping websites)

The problem is I don't how I can efficiently build the MySQL query based on these inputs because some of the Mysql columns are JSON.

Here is the separate SQL query:

// select rows that contains subject test or test1

SELECT *

FROM `cushbu_art`

WHERE subject IN ('test','test1')

// select rows that contains medium is paper or food

SELECT *

FROM `cushbu_art`

WHERE (JSON_CONTAINS(medium, '["paper"]')

OR JSON_CONTAINS(medium, '["food"]'))

Here is a sample input with two parameters (subject and medium)

{

"subject":["test","test1"],

"medium":["paper","wood"],

"category":"",

"material":"",

"style":""

}

Note: input and output are in JSON (REST API)

db.js

function(req, res) {

var sql = '';

if(req.body.subject) {

sql+=//PREPARE SUBJECT QUERY

}

if(req.body.medium) {

sql+=//PREPARE QUERY

}

//FINAL SQL QUERY HERE;

db.query(sql, function(error, result) {

console.log(result);

});

}

解决方案function(req,res){

var sql = 'SELECT * FROM `cushbu_art`';

//Check if only on is set

if(req.body.subject && !req.body.medium){

var subjectJoin=req.body.subject.join(',');

sql+='WHERE subject IN ('+subjectJoin+')';

}

//Check if only on is set

if(req.body.medium && !req.body.subject){

sql+='WHERE (JSON_CONTAINS(medium,'+req.body.medium[0]+') OR JSON_CONTAINS(medium,'+req.body.medium[1]+')';

}

if(req.body.medium && req.body.subject){

var subjectJoin=req.body.subject.join(',');

sql+='WHERE subject IN ('+subjectJoin+') AND (JSON_CONTAINS(medium,'+req.body.medium[0]+') OR JSON_CONTAINS(medium,'+req.body.medium[1]+')';

}

//FINAL SQL QUERY HERE';

db.query(sql,function(error,result){

console.log(result);

});

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值