I am working on a MySQl data base and have several tables that I need to join based on a temporary table that I created (layer_2).
Each table that I join has the join key for the next table;
E.g. layer_2 joins with "colegios" table, then the result will have the join key for the next table "ciudades". and finally the result will have the Join key for the next table "departamentos".
from what I got it works but I want to know if there is a way to simplify this?
Select
cuestionario_id,
tiempo,
nro_preguntas,
nro_preguntas_correctas,
tipo_usuario,
fecha_creacion_cuestionario,
con_tiempo,
det_cuestionarios_id,
respuesta_seleccionada,
pregunta_id,
enunciado,
respuesta_correcta,
usuarios_id,
dominio_correo,
tipo_institucion,
materia,
tematica,
area,
nombre_colegios,
direccion_colegios,
nombre_ciudades,
redsaber.departamentos.nombre as nombre_departamentos
From
(
Select
cuestionario_id,
tiempo,
nro_preguntas,
nro_preguntas_correctas,
cuestionable_id,
tipo_usuario,
fecha_creacion_cuestionario,
con_tiempo,
det_cuestionarios_id,
respuesta_seleccionada,
pregunta_id,
enunciado,
respuesta_correcta,
usuarios_id,
dominio_correo,
cole_ciud_id,
tipo_institucion,
materia,
tematica,
area,
combine_ciudad_id,
nombre_colegios,
direccion_colegios,
redsaber.ciudades.nombre as nombre_ciudades,
departamento_id
From
(Select
cuestionario_id,
tiempo,
nro_preguntas,
nro_preguntas_correctas,
cuestionable_id,
tipo_usuario,
fecha_creacion_cuestionario,
con_tiempo,
det_cuestionarios_id,
respuesta_seleccionada,
pregunta_id,
enunciado,
respuesta_correcta,
usuarios_id,
dominio_correo,
cole_ciud_id,
tipo_institucion,
materia,
tematica,
area,
ifnull(redsaber.colegios.ciudad_id,cole_ciud_id) as combine_ciudad_id,
redsaber.colegios.nombre as nombre_colegios,
redsaber.colegios.direccion as direccion_colegios
From layer_2
Left Join redsaber.colegios on layer_2.cole_ciud_id = redsaber.colegios.id
AND tipo_institucion = 'Colegio') as layer_3
Left Join redsaber.ciudades on combine_ciudad_id = redsaber.ciudades.id) as layer_4
Left Join redsaber.departamentos on departamento_id = redsaber.departamentos.id
I have a query and am using left joins. I have the left join clause as follows:
left outer join ( select pup.brokerage_code, pcz.zip, count (pup.aggregate_id) as VerifiedAgentCount
from partner_user_profiles pup
join partner_user_roles pure on pure.user_profile_id = pup.id
join profile_coverage_zips pcz on pcz.profile_id = pup.id
where lower(pure.role) = 'agent'
and pup.verification_status like 'Verified%'
group by pup.brokerage_code, pcz.zip) vac on vac.brokerage_code = b.brokerage_code and pcz.zip = bcz.zip
However I am getting the error message saying that I am missing the FROM entry clause for "pcz" however I aliased the table in the join clause so I am not sure what is wrong.
You have defined the table alias pcz within the sub-select however the alias no longer exists when the outside the sub-select. At the point you have used it the appropriate alias is the one for the entire sub-select, in this case vac. So: vac.zip = = bcz.zip
left outer join ( select pup.brokerage_code, pcz.zip, count (pup.aggregate_id) as VerifiedAgentCount
from partner_user_profiles pup
join partner_user_roles pure on pure.user_profile_id = pup.id
join profile_coverage_zips pcz on pcz.profile_id = pup.id
where lower(pure.role) = 'agent'
and pup.verification_status like 'Verified%'
group by pup.brokerage_code, pcz.zip
) vac on vac.brokerage_code = b.brokerage_code
and vac.zip = bcz.zip
am having a layout which is working fine , except for one part ,
If we use this layout to view or print any added document (AR Invoice) it will ring the write data and records.
but if the user click view or print before adding the document to the system , or if the document was saved as draft then : a random records will come into the layout , in a very randomly way , meaning if close the view and open it again another record different than the precious shown one will come .
What am looking for is simple as i thought , if a user tried to view or print a document thats not added into system then show blank page ,
any help ?
here is the query am using in CR
SELECT ohem.[U_Employee_Code] as'Cashier',OUSR.USER_CODE, OUSR.U_NAME,OUDG.[Code],OUDG.Phone1,OUDG.Phone2, OINV.DocEntry,oinv.docnum, OINV.DocType, OINV.DocStatus, OINV.InvntSttus, OINV.DocDate, OINV.DocDueDate, OINV.CardCode, nnm1.seriesname,
OINV.Address2, OINV.Printed, OINV.CardName, OINV.U_Address, OINV.NumAtCard, OINV.VatSum, OINV.DiscPrcnt, OINV.DiscSum, OINV.DocTotal, OINV.DocRate, OINV.u_deldate,
OINV.ReceiptNum, OINV.GroupNum, OINV.OwnerCode,OINV.JrnlMemo, OINV.VatPaid, OINV.Address2 AS Expr2, OINV.U_CUSTNAME1 as 'Customer Name' , OINV.U_PHONE1, OINV.ExepAmnt, OINV.ExepAmntSC, OINV.ExepAmntFC, OINV.VatDate,OINV.TotalExpns,
OINV.PaidSum, OINV.OwnerCode, OINV.BillToOW, OINV.ShipToOW, OINV.RetInvoice, OINV.ReqName, OINV.Requester, INV1.ItemCode, INV1.Dscription, INV1.Quantity, inv1.PriceBefDi,
INV1.SubCatNum, INV1.ShipDate, INV1.Price, INV1.Currency, INV1.Rate, INV1.DiscPrcnt AS Expr1, INV1.LineTotal, INV1.OpenSum, INV1.VatPrcnt, INV1.PriceAfVAT,
INV1.unitMsr, OINV.TaxDate, INV1.GTotal, OINV.Comments, OCTG.PymntGroup, OINV.LicTradNum, INV1.BaseDocNum, INV1.LineVat, OINV.WTSum, oinv.u_cancelled,
OCRN.CurrName, oslp.SlpName,OUDG.Phone1,OUDG.phone2,
oinv.u_empid as'Sales man',OUDG.Phone1 as 'Branch Phone',OUDG.phone2 as 'Customer Support Phone',OINV.U_PHONE1 as 'Customer Phone',inv1.shipdate as 'Item Delivery Date', OINV.TotalExpns AS 'FREIGHT CHARGES',OINV.U_Address as 'Customer Address',oinv.UpdateDate, OINV.DocEntry
FROM OINV INNER JOIN
INV1 ON OINV.DocEntry = INV1.DocEntry INNER JOIN
OUSR ON OINV.UserSign = OUSR.USERID INNER JOIN
OCTG ON OINV.GroupNum = OCTG.GroupNum INNER JOIN
OCRN ON OINV.DocCur = OCRN.CurrCode inner join
oslp on oinv.SlpCode = oslp.SlpCode INNER JOIN
OUDG ON OUSR.[DfltsGroup] = OUDG.[Code] inner join
nnm1 on OINV.series = nnm1.series LEFT JOIN
OHEM on OUSR.[userId] = OHEM.[USERID]
where OINV.DocEntry = {?DocKey#}
the solution is to use ObjectId to determine if the source is system document or draft . this is it
if {?ObjectId#} =13
SELECT ohem.[U_Employee_Code] as'Cashier',OUSR.USER_CODE, OUSR.U_NAME,OUDG.[Code],OUDG.Phone1,OUDG.Phone2, OINV.DocEntry,oinv.docnum, OINV.DocType, OINV.DocStatus, OINV.InvntSttus, OINV.DocDate, OINV.DocDueDate, OINV.CardCode, nnm1.seriesname,
OINV.Address2, OINV.Printed, OINV.CardName, OINV.U_Address, OINV.NumAtCard, OINV.VatSum, OINV.DiscPrcnt, OINV.DiscSum, OINV.DocTotal, OINV.DocRate, OINV.u_deldate,
OINV.ReceiptNum, OINV.GroupNum, OINV.OwnerCode,OINV.JrnlMemo, OINV.VatPaid, OINV.Address2 AS Expr2, OINV.U_CUSTNAME1 as 'Customer Name' , OINV.U_PHONE1, OINV.ExepAmnt, OINV.ExepAmntSC, OINV.ExepAmntFC, OINV.VatDate,OINV.TotalExpns,
OINV.PaidSum, OINV.OwnerCode, OINV.BillToOW, OINV.ShipToOW, OINV.RetInvoice, OINV.ReqName, OINV.Requester, INV1.ItemCode, INV1.Dscription, INV1.Quantity, inv1.PriceBefDi,
INV1.SubCatNum, INV1.ShipDate, INV1.Price, INV1.Currency, INV1.Rate, INV1.DiscPrcnt AS Expr1, INV1.LineTotal, INV1.OpenSum, INV1.VatPrcnt, INV1.PriceAfVAT,
INV1.unitMsr, OINV.TaxDate, INV1.GTotal, OINV.Comments, OCTG.PymntGroup, OINV.LicTradNum, INV1.BaseDocNum, INV1.LineVat, OINV.WTSum, oinv.u_cancelled,
OCRN.CurrName, oslp.SlpName,OUDG.Phone1,OUDG.phone2,
oinv.u_empid as'Sales man',OUDG.Phone1 as 'Branch Phone',OUDG.phone2 as 'Customer Support Phone',OINV.U_PHONE1 as 'Customer Phone',inv1.shipdate as 'Item Delivery Date', OINV.TotalExpns AS 'FREIGHT CHARGES',OINV.U_Address as 'Customer Address',oinv.UpdateDate
FROM OINV INNER JOIN
INV1 ON OINV.DocEntry = INV1.DocEntry INNER JOIN
OUSR ON OINV.UserSign = OUSR.USERID INNER JOIN
OCTG ON OINV.GroupNum = OCTG.GroupNum INNER JOIN
OCRN ON OINV.DocCur = OCRN.CurrCode inner join
oslp on oinv.SlpCode = oslp.SlpCode INNER JOIN
OUDG ON OUSR.[DfltsGroup] = OUDG.[Code] inner join
nnm1 on OINV.series = nnm1.series LEFT JOIN
OHEM on OUSR.[userId] = OHEM.[USERID]
where OINV.DocEntry = {?DocKey#}
else select ' '
I am trying to create a view that includes columns froms several tables.
This is what it looks like:
And this is my query:
SELECT
Billing.WebPortalBilling.WebPortalBillingId,
Billing.WebPortalBilling.CorporationId,
Billing.WebPortalBilling.TokenId,
Billing.WebPortalBilling.GatewaySupportFee,
Billing.WebPortalBilling.GatewayPerTransactionFee,
Billing.WebPortalBilling.PortalPerCustomerFee,
Billing.WebPortalBilling.PortalSupportFee,
Customer.Account.AccountNumber,
Billing.WebPortalBilling.IsActive,
Customer.Customer.Name,
Customer.Customer.TaxCode,
Company.CorporationStructure.Branch
FROM
Company.CorporationStructure
RIGHT OUTER JOIN
Customer.Account ON Company.CorporationStructure.CorporationStructureId = Customer.Account.CorporationStructureId
RIGHT OUTER JOIN
Customer.Customer ON Company.CorporationStructure.Branch = Customer.Customer.Branch
RIGHT OUTER JOIN
Billing.WebPortalBilling ON Customer.Account.CorporationId = Billing.WebPortalBilling.CorporationId
WHERE
(Billing.WebPortalBilling.IsActive = 1)
It's only returning 1 record, which is not correct. I'm trying to tie the Customer's name back to the WebPortalBilling table along with the account number and branth in the other two tables.
I'm new to sql, so be kind.
Thanks!
As commented the where is killing the outer
Try
SELECT
Billing.WebPortalBilling.WebPortalBillingId,
Billing.WebPortalBilling.CorporationId,
Billing.WebPortalBilling.TokenId,
Billing.WebPortalBilling.GatewaySupportFee,
Billing.WebPortalBilling.GatewayPerTransactionFee,
Billing.WebPortalBilling.PortalPerCustomerFee,
Billing.WebPortalBilling.PortalSupportFee,
Customer.Account.AccountNumber,
Billing.WebPortalBilling.IsActive,
Customer.Customer.Name,
Customer.Customer.TaxCode,
Company.CorporationStructure.Branch
FROM
Company.CorporationStructure
RIGHT OUTER JOIN
Customer.Account ON Company.CorporationStructure.CorporationStructureId = Customer.Account.CorporationStructureId
RIGHT OUTER JOIN
Customer.Customer ON Company.CorporationStructure.Branch = Customer.Customer.Branch
RIGHT OUTER JOIN Billing.WebPortalBilling
ON Customer.Account.CorporationId = Billing.WebPortalBilling.CorporationId
AND Billing.WebPortalBilling.IsActive = 1
Try this, I think left joins are clearer.
SELECT
B.WebPortalBillingId,
B.CorporationId,
B.TokenId,
B.GatewaySupportFee,
B.GatewayPerTransactionFee,
B.PortalPerCustomerFee,
B.PortalSupportFee,
C.AccountNumber,
B.IsActive,
C.Name,
C.TaxCode,
CS.Branch
FROM Customer.Customer C
LEFT JOIN Company.CorporationStructure CS ON CS.Branch = C.Branch
LEFT JOIN Customer.Account A ON CS.CorporationStructureId = A.CorporationStructureId
LEFT JOIN Billing.WebPortalBilling B ON A.CorporationId = B.CorporationId
WHERE B.IsActive = 1
I have this select clause that is working perfect:
SELECT
"Aspectos"."ID" AS "Aspecto Normativo ID",
"Aspectos"."Aspecto" AS "Aspecto Normativo",
"Fatores"."ID", "Fatores"."Fator" AS "Fator Normativo",
"Diagnostico"."Vinculo_Final",
"Fatores_1"."ID",
"Fatores_1"."Fator" AS "Fator Determinativo",
"Aspectos_1"."ID" AS "Aspecto Determinativo ID",
"Aspectos_1"."Aspecto" AS "Aspecto Determinativo",
Count("Itens"."ID") AS "No Itens",
Count("Itens"."ID") AS "Pri"
FROM "Diagnostico" INNER JOIN ("Aspectos" AS "Aspectos_1"
INNER JOIN (("Fontes" INNER JOIN "Itens" ON "Fontes"."ID" = "Itens"."Fonte")
INNER JOIN ("Fatores" AS "Fatores_1"
INNER JOIN ("Aspectos"
INNER JOIN ("Vinculos"
INNER JOIN "Fatores"
ON "Vinculos"."Fator_Normativo" = "Fatores"."ID")
ON ("Aspectos"."ID" = "Fatores"."Aspecto")
AND ("Aspectos"."ID" = "Fatores"."Aspecto"))
ON "Fatores_1"."ID" = "Vinculos"."Fator_Determinativo")
ON "Itens"."ID" = "Vinculos"."Item")
ON "Aspectos_1"."ID" = "Fatores_1"."Aspecto")
ON "Diagnostico"."ID" = "Vinculos"."Diagnostico_ID"
GROUP BY "Aspectos"."ID", "Aspectos"."Aspecto",
"Fatores"."ID", "Fatores"."Fator",
"Diagnostico"."Vinculo_Final",
"Fatores_1"."ID",
"Fatores_1"."Fator",
"Aspectos_1"."ID",
"Aspectos_1"."Aspecto"
ORDER BY "Aspectos"."ID", "Aspectos_1"."ID",
"Fatores"."Fator", "Fatores_1"."Fator";
But when I try to CREATE A VIEW with this same select I'm getting thuis error:
ERROR: column "ID" specified more than one time
Can anybody help me on this.
Thanks
You have "Fatores"."ID" (line 4) and "Fatores_1"."ID" (line 6). Give them different aliases.
For such complex queries it is recommended to have only 1 (one) column in per line in the statement for better visibility. Also it is recommended to always give aliases to the columns.