TypeORM-NestJs Join on Json column - mysql

join two mysql tables using typeorm-NestJs
where table 1(t1) is normal table
& table 2(t2) has a column which containts JSON data
now I need to join them based on t1.id == t2.column_name.id
but I am getting error on that query
query I am using :-
const results = await this.connection.createQueryBuilder(ABCEntity,'t1')
.innerJoinAndMapMany('t1.Id',xyzEntity,'t2','t1.Id = t2.column_name.$.Id')
.where('t1.Id = :Id',{Id: id})
.getMany()
.catch(err => console.log(err));
Error I am getting :-
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.Id WHERE `t1`.`Id` = 'b6D812aF-9e22-4a5a-a292-6rc5021bfv0a'' at line 1",
sqlState: '42000',

what worked for me was, everything in backticks
for eg : `t1.Id = t2.column_name->'$.Id'
const results = await this.connection.createQueryBuilder(ABCEntity,'t1')
.innerJoinAndMapMany('t1.Id',xyzEntity,'t2',`t1.Id = t2.column_name->'$.Id'`)
.where('t1.Id = :Id',{Id: id})
.getMany()
.catch(err => console.log(err));

Related

'ER_PARSE_ERROR' You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version

I created in my model the const getbypage:
const getByPage = (page = 1, limit = 10) => {
return executeQuery(
'select * from clientes limit ? offset = ?',
[limit, (page-1) * limit]
);
}
in the controller:
router.get('/', async (req, res) => {
try {
const clients = await getByPage();
res.render('clients/list', { arrClients: clients });
} catch (err) {
console.log(err);
}
});
and the error is:
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlState: '42000',
sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '= 0' at line 1",
sql: 'select * from clientes limit 10 offset = 0'
}
GET /clients - - ms - -
CAN SOMEBODY HELP ME?
https://dev.mysql.com/doc/refman/8.0/en/select.html shows you the reference documentation for the LIMIT clause:
[LIMIT {[offset,] row_count | row_count OFFSET offset}]
There's no = in the syntax. You should just use OFFSET ?.
WRONG:
select * from clientes limit ? offset = ?
RIGHT:
select * from clientes limit ? offset ?

Update a single record in database CakePHP

I am trying to update a single record of the database with the function "updateAll", and filtering by a single "id".
$this->Factura->updateAll(
array(
'Factura.I_COBRADO' => $factura['Factura']['I_TOTAL'],
'Factura.L_COBRADA' => 1,
'Factura.FH_COBRO' => date('Y-m-d H:i:s'),
'Factura.S_FORMAPAGO' => 'tarjeta',
'Factura.FK_FORMAPAGOCOBRO' => 41
),
array(
'Factura.PK_FACTURA' => $factura['Factura']['PK_FACTURA'])
)
But I get this error:
Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '15:10:55, Factura.S_FORMAPAGO = tarjeta, Factura.FK_FORMAPAGOCOBRO = 41 ' at line 1
SQL Query: UPDATE itramit_daily_desarrollo.facturas AS Factura LEFT JOIN itramit_daily_desarrollo.expedientes AS Expediente ON (Factura.FK_EXPEDIENTE = Expediente.PK_EXPEDIENTE) LEFT JOIN itramit_daily_desarrollo.expedientes AS ExpedienteFactura ON (Factura.FK_EXPEDIENTE = ExpedienteFactura.PK_EXPEDIENTE) LEFT JOIN itramit_daily_desarrollo.municipios AS Municipio ON (Factura.FK_MUNICIPIO = Municipio.PK_MUNICIPIO) LEFT JOIN itramit_daily_desarrollo.valoraciones AS Valoracione ON (Factura.FK_VALORACION = Valoracione.PK_VALORACION) LEFT JOIN itramit_daily_desarrollo.liquidaciones AS Liquidacione ON (Factura.FK_LIQUIDACION = Liquidacione.PK_LIQUIDACION) LEFT JOIN itramit_daily_desarrollo.formaspagoscobros AS Formaspagoscobro ON (Factura.FK_FORMAPAGOCOBRO = Formaspagoscobro.PK_FORMAPAGOCOBRO) SET Factura.I_COBRADO = 165.00, Factura.L_COBRADA = 1, Factura.FH_COBRO = 2021-08-16 15:10:55, Factura.S_FORMAPAGO = tarjeta, Factura.FK_FORMAPAGOCOBRO = 41 WHERE Factura.PK_FACTURA = 166569
Running your query through MySQL Workbench, I see that
Factura.FH_COBRO = 2021-08-16 15:10:55
is the cause of the syntax error. It appears that CakePHP does not add quotes around the data value.
Try:
'Factura.FH_COBRO' => "'" + date('Y-m-d H:i:s') + "'",
'Factura.S_FORMAPAGO' => "'tarjeta'",

Pass multiple id(s) in query string and get data for them in mysql in node js

I have a get API in nodejs , which gets string of variables as query string ( delimited by ",") as follows
const mac = req.query.mac;
console.log(mac); // 00:11:22:33:FF:EE,11:11:22:33:FF:EE
var sql = mysql.format("SELECT * FROM user_email WHERE macId IN ?",[mac]);
connection.query(sql, function(err, row) ...{ ... .. }
But i am getting errors
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''00:11:22:33:FF:EE,11:11:22:33:FF:EE'' at line 1",
sqlState: '42000',
index: 0,
sql: "SELECT * FROM user_email WHERE macId IN '00:11:22:33:FF:EE,11:11:22:33:FF:EE'"
}
Someone please help !!
your mistake is in converting mac from string to array
[mac]
won't convert it to a string. try this instead:
const mac = req.query.mac;
const macArr = mac.split(',');
var sql = mysql.format("SELECT * FROM user_email WHERE macId IN (?)", macArr);
connection.query(sql, function(err, row) ...{ ... .. }

How to insert one query result to another query as an input

When I try to run a query I am getting 500 Internal Error. I want to insert query2 result to query as a data.
Query:
exports.create = async (req, res) => {
try {
const connection = await mysql.createConnection(config.mysql.credentials);
var query2='select MAX(orders) from pdb_product';
const query = `insert into pdb_product (product_code, description, active, third_party,
orders) values ("${req.body.product_code}", "${req.body.description}", ${(req.body.active == 'on' ? 1 : 0)}, ${(req.body.third_party == 'on' ? 1 : 0)}, ${query2});`;
await connection.query(query);
res.redirect('/products');
} catch (e) {
utils.error500(req, res, e.message);
}
};
The error I am getting:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select MAX(orders) from pdb_product)' at line 1
How can I resolve this?
You are missing a '(' bracket before the query2 parameter:
const query = `insert into pdb_product (product_code, description, active, third_party,
orders)
values ("${req.body.product_code}",
"${req.body.description}",
${(req.body.active == 'on' ? 1 : 0)},
${(req.body.third_party == 'on' ? 1 : 0)},
(${query2}));`;

Error trying to turn raw sql into laravel query builder

I am trying to turn this very long raw sql into laravel query builder and encounter an error.
This is the original raw sql
sql = "select d.doc_Code,d.seq,p.seq2,d.product_code,d.name_t,d.dwg_file,p.book,concat(p.book,'-',p.seq) as job_book,h.sale_code,h.sale_name,h.ref_code,h.ref_name,h.priority,p.code,p.in_time,wt_date,p.job_status,d.status,DATEDIFF(now(),p.in_time) as gdays,DATEDIFF(h.due_date,now()) as gdue_days,h.due_date,h.start_date as start_datex from jt_p as p inner join jt_d as d on (p.doc_code=d.doc_code and p.book=d.book and p.seq=d.seq and p.in_time is not null and p.wt_date is null and p.job_status not in('Z','C') and p.code<>'M' and d.status <>'C') inner join jt_h as h on(h.doc_code =p.doc_code and h.book=p.book)"
Here is the laravel query builder:
$jt_p = DB::table('jt_p')
->join('jt_d', function($join){
$join->on('jt_p.doc_code', '=', 'jt_d.doc_code');
$join->on('jt_p.book','=','jt_d.book');
$join->on('jt_p.seq','=','jt_d.seq');
})
->where('jt_p.in_time','!=','')
->where('jt_p.wt_time','=','')
->where('jt_p.job_status',DB::raw('not in ("Z","C")'))
->where('jt_p.code','!=','M')
->where('jt_d.status','!=','C')
->join('jt_h', function($join){
$join->on('jt_h.doc_code', '=', 'jt_p.doc_code');
$join->on('jt_p.book','=','jt_h.book');
})
->select('jt_d.doc_code','jt_d.seq','jt_p.seq2','jt_d.product_code','jt_d.name_t','jt_d.dwg_file','jt_p.book',
'jt_h.sale_code','jt_h.sale_name','jt_h.ref_code','jt_h.ref_name','jt_h.priority','jt_p.code','jt_p.in_time','jt_p.wt_time',
'jt_p.job_status','jt_d.status',DB::raw("DATEDIFF(now(),jt_p.in_time) as gdays"),
DB::raw("DATEDIFF(jt_h.due_date,now()) as gdue_days"),
'jt_h.due_date','jt_h.start_date as start_datex')
->get();
return $jt_p;
This is the error message:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'not in ("Z","C") and `jt_p`.`code` != ? and `jt_d`.`status` != ?' at line 1 (SQL: select `jt_d`.`doc_code`, `jt_d`.`seq`, `jt_p`.`seq2`, `jt_d`.`product_code`, `jt_d`.`name_t`, `jt_d`.`dwg_file`, `jt_p`.`book`, `jt_h`.`sale_code`, `jt_h`.`sale_name`, `jt_h`.`ref_code`, `jt_h`.`ref_name`, `jt_h`.`priority`, `jt_p`.`code`, `jt_p`.`in_time`, `jt_p`.`wt_time`, `jt_p`.`job_status`, `jt_d`.`status`, DATEDIFF(now(),jt_p.in_time) as gdays, DATEDIFF(jt_h.due_date,now()) as gdue_days, `jt_h`.`due_date`, `jt_h`.`start_date` as `start_datex` from `jt_p` inner join `jt_d` on `jt_p`.`doc_code` = `jt_d`.`doc_code` and `jt_p`.`book` = `jt_d`.`book` and `jt_p`.`seq` = `jt_d`.`seq` inner join `jt_h` on `jt_h`.`doc_code` = `jt_p`.`doc_code` and `jt_p`.`book` = `jt_h`.`book` where `jt_p`.`in_time` != and `jt_p`.`wt_time` = and `jt_p`.`job_status` = not in ("Z","C") and `jt_p`.`code` != M and `jt_d`.`status` != C)
Change this line of code
->where('jt_p.job_status',DB::raw('not in ("Z","C")'))
to
->whereNotIn('jt_p.job_status',["Z","C"])
You need also to use IsNull IsNotNull
$jt_p = DB::table('jt_p')
->join('jt_d', function($join){
$join->on('jt_p.doc_code', '=', 'jt_d.doc_code');
$join->on('jt_p.book','=','jt_d.book');
$join->on('jt_p.seq','=','jt_d.seq');
})
->whereNotNull('jt_p.in_time')
->whereNull('jt_p.wt_time')
->whereNotIn('jt_p.job_status',["Z","C"])
->where('jt_p.code','!=','M')
->where('jt_d.status','!=','C')
->join('jt_h', function($join){
$join->on('jt_h.doc_code', '=', 'jt_p.doc_code');
$join->on('jt_p.book','=','jt_h.book');
})
->select('jt_d.doc_code','jt_d.seq','jt_p.seq2','jt_d.product_code','jt_d.name_t','jt_d.dwg_file','jt_p.book',
'jt_h.sale_code','jt_h.sale_name','jt_h.ref_code','jt_h.ref_name','jt_h.priority','jt_p.code','jt_p.in_time','jt_p.wt_time',
'jt_p.job_status','jt_d.status',DB::raw("DATEDIFF(now(),jt_p.in_time) as gdays"),
DB::raw("DATEDIFF(jt_h.due_date,now()) as gdue_days"),
'jt_h.due_date','jt_h.start_date as start_datex')
->get();
return $jt_p;