In my Django project i have to implement a complex RAW query for extract data, for doing this i use the raw django function.
The original query is:
SELECT FT."Riferimento1", FT."Riferimento2", "CodProdotto", "QuantitaFatturata", "PrezzoUnit", "DataFattura", "NumeroFattura", "CodCli"
FROM public.idocuments_as_fatturetestata FT
LEFT JOIN public.idocuments_as_fatturerighe FR ON FT."Riferimento1" = FR."Riferimento1" AND FT."Riferimento2" = FR."Riferimento2"
WHERE FT."CodCli" = '12192';
if i run directly in pgadmin SQL all was done
In django i implement in this fashion:
>>> from idocuments.models import as_fatturetestata as asf
>>> a = asf.objects.raw("SELECT FT."Riferimento1",FT."Riferimento2","CodProdotto","QuantitaFatturata","PrezzoUnit","DataFattura","NumeroFattura","CodCli" FROM public.idocuments_as_fatturetestata FT LEFT JOIN public.idocuments_as_fatturerighe FR ON FT."Riferimento1" = FR."Riferimento1" AND FT."Riferimento2" = FR."Riferimento2" WHERE FT."CodCli" = '12192'")
but i get:
SyntaxError: invalid syntax
maybe the problem is how to manage quotes but i don't understand how transport the sql query into raw directive.
Someone can help me please?
so many thanks in advance
Try using single quotes and escaping the single quotes within the string with \:
a = asf.objects.raw('"SELECT FT."Riferimento1",FT."Riferimento2","CodProdotto","QuantitaFatturata","PrezzoUnit","DataFattura","NumeroFattura","CodCli" FROM public.idocuments_as_fatturetestata FT LEFT JOIN public.idocuments_as_fatturerighe FR ON FT."Riferimento1" = FR."Riferimento1" AND FT."Riferimento2" = FR."Riferimento2" WHERE FT."CodCli" = \'12192\'"')
Related
I have an MS Access Query:
'''UPDATE MyFloridaNetDataDump INNER JOIN RepoVoipAcsNonRecurring ON
'''MyFloridaNetDataDump.service_modified = RepoVoipAcsNonRecurring.Validation
'''SET RepoVoipAcsNonRecurring.Invoice = MyFloridaNetDataDump.Invoice_modified,
'''RepoVoipAcsNonRecurring.Amount = '''Round(MyFloridaNetDataDump.billable_charge*RepoVoipAcsNonRecurring.Percentage,2),
'''RepoVoipAcsNonRecurring.Billing Cycle = MyFloridaNetDataDump.bill_cycle;
I need to convert it to SQL, which I'm using in a .net application.
I have been able to convert most of the query, but when I try to perform the multiplication I get errors depending on what I leave in. Meaning if I take the ROUND function out it doesn't like the * multiplication. If I remove the multiplication line, the query runs.
'''UPDATE MyFloridaNetDataDump
'''SET MyFloridaNetDataDump.InvoiceModified = RepoVoipAcsNonRecurring.Invoice,
'''MyFloridaNetDataDump.BillableCharge * RepoVoipAcsNonRecurring.Percentage = '''RepoVoipAcsNonRecurring.Amount,
'''MyFloridaNetDataDump.BillCycle = RepoVoipAcsNonRecurring.BillingCycle
'''FROM RepoVoipAcsNonRecurring
'''WHERE MyFloridaNetDataDump.ServiceModified = RepoVoipAcsNonRecurring.Validation
I think you inverse all of your set columns
I would suggest you to do like this
UPDATE r
SET
Invoice = m.InvoiceModified,
Amount = Round(m.billablecharge*r.Percentage,2),
[BillingCycle] = m.billCycle
FROM
MyFloridaNetDataDump m
INNER JOIN RepoVoipAcsNonRecurring r ON m.serviceModified = r.Validation
This is the SQL I am trying to create with JOOQ -
select distinct(kmp.*) from office_all_company_kmp kmp
inner join company_kmp companykmp on kmp.id=companykmp.kmp_id
where companykmp.company_id=?1
I am writing code in Kotlin. I had 2 issues doing this -
In the select clause, unless I add a .asList() to the fields array, I couldn't get it compiling.
The fetch mapper had to be handcoded. Is there a way I can use do this without writing all that code? I can map records fetched back from one table without writing any mapping.
Here's what I am talking about:
fun OfficeAllCompanyKmpDao.findByCompany(companyId: UUID): List<OfficeAllCompanyKmp> =
this.ctx()
.selectDistinct(OFFICE_ALL_COMPANY_KMP.fields().asList()) // without the asList() it wouldn't compile
.from(OFFICE_ALL_COMPANY_KMP)
.join(COMPANY_KMP).on(OFFICE_ALL_COMPANY_KMP.ID.eq(COMPANY_KMP.KMP_ID))
.where(COMPANY_KMP.COMPANY_ID.eq(companyId))
.fetch { // how do I write the mapper without manually writing code like the below?
OfficeAllCompanyKmp(
id = it[OFFICE_ALL_COMPANY_KMP.ID],
officeId = it[OFFICE_ALL_COMPANY_KMP.OFFICE_ID],
din = it[OFFICE_ALL_COMPANY_KMP.DIN],
pan = it[OFFICE_ALL_COMPANY_KMP.PAN],
name = it[OFFICE_ALL_COMPANY_KMP.NAME],
dateOfBirth = it[OFFICE_ALL_COMPANY_KMP.DATE_OF_BIRTH],
address = it[OFFICE_ALL_COMPANY_KMP.ADDRESS],
email = it[OFFICE_ALL_COMPANY_KMP.EMAIL],
kmpDetails = it[OFFICE_ALL_COMPANY_KMP.KMP_DETAILS],
createdTimestamp = it[OFFICE_ALL_COMPANY_KMP.CREATED_TIMESTAMP],
updatedTimestamp = it[OFFICE_ALL_COMPANY_KMP.UPDATED_TIMESTAMP],
versionNo = it[OFFICE_ALL_COMPANY_KMP.VERSION_NO],
createdUserId = it[OFFICE_ALL_COMPANY_KMP.CREATED_USER_ID],
updatedUserId = it[OFFICE_ALL_COMPANY_KMP.UPDATED_USER_ID]
)
}
A better approach than inner joining and then removing duplicates again would be to semi join your other table using IN or EXISTS:
this.ctx()
.selectFrom(OFFICE_ALL_COMPANY_KMP)
.where(OFFICE_ALL_COMPANY_KMP.ID.`in`(
select(COMPANY_KMP.KMP_ID)
.from(COMPANY_KMP)
.where(COMPANY_KMP.COMPANY_ID.eq(companyId)))
.fetchInto(OfficeAllCompanyKmp::class.java)
Or, alternatively, use jOOQ's synthetic LEFT SEMI JOIN syntax (see also this blog post for an explanation for this syntax, or this one for joins in general, or Wikipedia's nice explanation about semi joins)
this.ctx()
.select()
.from(OFFICE_ALL_COMPANY_KMP)
.leftSemiJoin(COMPANY_KMP)
.on(OFFICE_ALL_COMPANY_KMP.ID.eq(COMPANY_KMP.KMP_ID))
.and(COMPANY_KMP.COMPANY_ID.eq(companyId))
.fetchInto(OfficeAllCompanyKmp::class.java)
Your problem 1) went away by using different jOOQ API, where you don't have to list all columns explicitly in SELECT. Your problem 2) is fixed easily by calling fetchInto() instead.
Hello! , i have an issue with an sql Call on laravel 5.5 using query builder. when i do this
$result = DB::table(self::$TABLA_COMPONENTE)
->join(self::$TABLA_ARCHIVOS ,self::$TABLA_COMPONENTE.'.com_id','=',self::$TABLA_ARCHIVOS.'.com_id')
->select(self::$TABLA_COMPONENTE.'.*',DB::raw('group_concat('.self::$TABLA_ARCHIVOS.'.ar_url) as com_archivos'))
->where(self::$TABLA_COMPONENTE.'.com_id',$id)->first();
i get the following error
SQLSTATE[42000]: Syntax error or access violation: 1140 Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause (SQL: select componente.*, group_concat(archivos.ar_url) as com_archivos from componente inner join archivos on componente.com_id = archivos.com_id where componente.com_id = 2 limit 1)
this is the raw sql i get by using ->toSql()
This is the sql with ->toSql()
"select `componente`.*, group_concat(archivos.ar_url) as com_archivos from `componente` inner join `archivos` on `componente`.`com_id` = `archivos`.`com_id` where `componente`.`com_id` = ?
And it works fine on Phpmyadmin.
i also tried using Group by with no luck.
If you could help me with a solution I would be very grateful!
This is actually mysql problem not laravel problem. Try add
->groupBy(self::$TABLA_COMPONENTE . '.id')
to you query.
EDITED: something like this one :
$result = DB::table(self::$TABLA_COMPONENTE)
->join(self::$TABLA_ARCHIVOS ,self::$TABLA_COMPONENTE.'.com_id','=',self::$TABLA_ARCHIVOS.'.com_id')
->select(self::$TABLA_COMPONENTE.'.*',DB::raw('group_concat('.self::$TABLA_ARCHIVOS.'.ar_url) as com_archivos'))
->groupBy(self::$TABLA_COMPONENTE . '.id')
->where(self::$TABLA_COMPONENTE.'.com_id',$id)->first();
note : it is not testet
How to convert this query :
SELECT pembelian_detail_tb.kode_beli, pembelian_detail_tb.kode_produk, produk_tb.nama, pembelian_detail_tb.jumlah
FROM pembelian_detail_tb
INNER JOIN produk_tb ON pembelian_detail_tb.kode_produk = produk_tb.kode_produk;
I have try many code, and i still got undefine.
Try this
$query = $this->db->select('pembelian_detail_tb.kode_beli, pembelian_detail_tb.kode_produk, produk_tb.nama, pembelian_detail_tb.jumlah')
->from('pembelian_detail_tb')
->join('produk_tb', 'pembelian_detail_tb.kode_produk = produk_tb.kode_produk', 'inner')
->get();
I like to use Query Bindings once a join is involved in a query:
https://www.codeigniter.com/userguide3/database/queries.html
search page for "query bindings"
this escapes values for you of course and if you need to debug dump $this->db->last_query();
Been trying to get the following query working for a few hours now and am running out of ideas. Can anyone spot where I'm going wrong. Any pointers much appreciated.
CalEvents = (List<CalEvent>)session.CreateSQLQuery(#"
SELECT *
FROM dbo.tb_calendar_calEvents
INNER JOIN dbo.tb_calEvents
ON (dbo.tb_calendar_calEvents.calEventID = dbo.tb_calEvents.id)
WHERE dbo.tb_calendar_calEvents.calendarID = 'theCalID'"
)
.AddEntity(typeof(CalEvent))
.SetInt64("theCalID", cal.id);
Error:
Kanpeki.NUnit.CalUserTest.Should_return_logged_in_user:
System.ArgumentException : Parameter theCalID does not exist as a
named parameter in [SELECT * FROM dbo.tb_calendar_calEvents INNER JOIN
dbo.tb_calEvents ON (dbo.tb_calendar_calEvents.calEventID =
dbo.tb_calEvents.id) WHERE dbo.tb_calendar_calEvents.calendarID =
'theCalID']
"SELECT * FROM dbo.tb_calendar_calEvents INNER JOIN dbo.tb_calEvents ON (dbo.tb_calendar_calEvents.calEventID = dbo.tb_calEvents.id) WHERE dbo.tb_calendar_calEvents.calendarID = 'theCalID'"
should be
"SELECT * FROM dbo.tb_calendar_calEvents INNER JOIN dbo.tb_calEvents ON (dbo.tb_calendar_calEvents.calEventID = dbo.tb_calEvents.id) WHERE dbo.tb_calendar_calEvents.calendarID = :theCalID"
= 'theCalID' should be written as = :theCalId; :theCalId is how you use named parameters even in Native SQL Queries.
You should remove the query.ExecuteUpdate() call.
Doing the query.List() is enough to issue the query on the session and return the result set.