1

I have a json request in this form:

{
"claimNo":["5454545","4554454","45884"]

}

the claimNo could hold any number of items(not restricted). I want to get the values and write a query to fetch data from a mysql db where claimNo = the values in the request. sample response:

 "claims": [
    {
        "claimNo": "4554454",
        "ClaimCause": "gjgiukhknl",
        "ClaimAmount": 45550,
    },
    {
        "claimNo": "5454545",
        "ClaimCause": "fdfdfdfdf",
        "ClaimAmount": 0,
    }
]

I can successfully loop through the request and display on terminal or even insert into the db with multiple ORs but that only works for a restricted array length.

 req.body.claimNo.forEach(element => {
    // console.log(element)

    let sql = 'SELECT * FROM  claims WHERE claimNo = ?'

    connection.query(sql,element,(err, rows, fields) => {
            if(!err){
                // return res.json({
                //     success:true,
                //     errorCode:"",
                //     errorDescription:"",
                //     claims:rows
                // })
                console.log(rows)
            }else
            console.log(err)


    } )
})

2 Answers 2

2

If I understand your question correctly, you're looking for a way to query MySQL database for multiple number of claimNo entries, and return the result as a single result.

Using MySQL IN() operator, you can write your query as select * from claims where claimNo in(?)

let sql = 'select * from claims where claimNo in(?)';

let claimNos = req.body.claimNo;

connection.query(sql, claimNos, (err, rows, fields) => {
  if(!err){
     // return res.json({
     //     success:true,
     //     errorCode:"",
     //     errorDescription:"",
     //     claims:rows
     // })
     console.log(rows)
 }else
   console.log(err)
})
Sign up to request clarification or add additional context in comments.

Comments

1

You don't need to send a separate request for each claimNo. You can you the IN operator instead. The following should work:

const claimsNo = claims.map(claim => claim.claimNo);

const sql = 'SELECT & FROM claims where claimNo IN (?)';
connection.query(sql, [ tableName, claimsNo ], (err, rows, fields) =>{
   ...
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.