简体   繁体   中英

How to assign values to a sql query inside multiple where clause and run query in single command

I have values array as:

const params = [
['2022-12-10', 'aaaaa', '2022-12-01', 'xhxha', '2022-12-10'],
['2022-12-11', 'ababa', '2022-12-01', 'xhxha', '2022-12-11'],
['2022-12-12', 'acaca', '2022-12-01', 'xhxha', '2022-12-12'],
['2022-12-13', 'adada', '2022-12-01', 'xhxha', '2022-12-13'],
];

const data = await db.query(`select id, title, DATE_FORMAT(end_date,"%Y-%m-%d") as end_date ABS(DATEDIFF(?, end_date))+1 as delay from chart 
where uid = ?
and date = ?
and project_uid = ?
and end_date = ?
and completed is true;
`, [params]);

I want to run this query, but all the values are being added to the 1st? (question mark). I want to have the the values to different? and get the result.

Also I do not want to run query inside for loop. How do I get the result here?

You can join to a parameters subquery. Since 8.0 you can use VALUES table constructor. Alternatively use SELECT.. UNION ALL in params subquery

select id, title, DATE_FORMAT(end_date,"%Y-%m-%d") as end_date ABS(DATEDIFF(?, end_date))+1 as delay
from (
  values
   row(date '2022-12-10', 'aaaaa', date '2022-12-01', 'xhxha', '2022-12-10'),
   row(date '2022-12-11', 'ababa', date '2022-12-01', 'xhxha', '2022-12-11'),
   row(date '2022-12-12', 'acaca', date '2022-12-01', 'xhxha', '2022-12-12'),
   row(date '2022-12-13', 'adada', date '2022-12-01', 'xhxha', '2022-12-13')
) params(p1, p2, p3, p4 ,p5)
join chart c
on c.uid = params.p1
and c.date = params.p2
and c.project_uid = params.p3
and c.end_date = params.p4
and c.completed is true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM