Is there a way to modify this query and make it more simple? - mysql-workbench

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

Related

Postgres Error: missing FROM-clause entry for table

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

How to apply distinct to perticular column and fetch all values from table in JPA(Criteria Builder)

I have written JPA query in that I want to apply distinct to only one column but here it is applying to all columns in table.
CriteriaBuilder cb = entityManager_gbl.getCriteriaBuilder();
CriteriaQuery<sourceTracking> cq = cb.createQuery(sourceTracking.class);
Root<sourceTracking> data1 = cq.from(sourceTracking.class);
Join<sourceTracking,status> joinobj=data1.join("sts");
Subquery<Number> subq=cq.subquery(Number.class);
Root<sourceTracking> sbf=subq.from(sourceTracking.class);
subq.select(cb.min(sbf.<Number>get("hopcount"))).groupBy(sbf.<String>get("message_id"));
cq.multiselect(cq.from(sourceTracking.class).get("message_id"));
cq.distinct(true);
cq.select(data1).orderBy(cb.asc(data1.get("message_id")));;
TypedQuery<sourceTracking> tquery = entityManager_gbl.createQuery(cq);
Here is my Hibernate query
select distinct sourcetrac0_.tablekey as tablekey1_2_, sourcetrac0_.alt_recipient_addr as alt_reci2_2_,
sourcetrac0_.alt_recipient_tried as alt_reci3_2_,sourcetrac0_.arrival_time as arrival_4_2_, sourcetrac0_.delivery_status as delivery5_2_, sourcetrac0_.dispatch_time as dispatch6_2_,
sourcetrac0_.hopcount as hopcount7_2_, sourcetrac0_.id as id8_2_, sourcetrac0_.id1 as id9_2_, sourcetrac0_.mail_orig_time as mail_or10_2_,
sourcetrac0_.mail_server as mail_se11_2_, sourcetrac0_.mailtype as mailtyp12_2_, sourcetrac0_.message_id as message13_2_, sourcetrac0_.nexthop as nexthop14_2_,
sourcetrac0_.precedence as precede15_2_, sourcetrac0_.receiver as receive16_2_, sourcetrac0_.securityclassification as securit17_2_, sourcetrac0_.sender as sender18_2_,
sourcetrac0_.subject as subject19_2_ from source_tracking sourcetrac0_ inner join status_table status2_ on sourcetrac0_.message_id=status2_.message_id
cross join source_tracking sourcetrac1_ order by sourcetrac0_.message_id asc,sourcetrac0_.hopcount asc.
I want to apply distinct to only one column here is what needed query
select distinct on(sourcetrac0_.message_id) sourcetrac0_.message_id,sourcetrac0_.tablekey as tablekey1_2_, sourcetrac0_.alt_recipient_addr as alt_reci2_2_,
sourcetrac0_.alt_recipient_tried as alt_reci3_2_,sourcetrac0_.arrival_time as arrival_4_2_, sourcetrac0_.delivery_status as delivery5_2_, sourcetrac0_.dispatch_time as dispatch6_2_,
sourcetrac0_.hopcount as hopcount7_2_, sourcetrac0_.id as id8_2_, sourcetrac0_.id1 as id9_2_, sourcetrac0_.mail_orig_time as mail_or10_2_,
sourcetrac0_.mail_server as mail_se11_2_, sourcetrac0_.mailtype as mailtyp12_2_, sourcetrac0_.message_id as message13_2_, sourcetrac0_.nexthop as nexthop14_2_,
sourcetrac0_.precedence as precede15_2_, sourcetrac0_.receiver as receive16_2_, sourcetrac0_.securityclassification as securit17_2_, sourcetrac0_.sender as sender18_2_,
sourcetrac0_.subject as subject19_2_ from source_tracking sourcetrac0_ inner join status_table status2_ on sourcetrac0_.message_id=status2_.message_id
cross join source_tracking sourcetrac1_ order by sourcetrac0_.message_id asc,sourcetrac0_.hopcount asc
That's no possible because DISTINCT is done on the result of the query. Read more here:
DISTINCT for only one Column

How to optimize a query with hard left join?

I have got a query
SELECT
"athlete"."id" AS "athlete_id"
FROM "athlete"
LEFT JOIN "athlete_in_game" ON athlete.id = athlete_in_game.id_athlete
LEFT JOIN "athlete_in_team" ON athlete.id = athlete_in_team.id_athlete
LEFT JOIN "game" ON
athlete_in_team.id_team = game.id_team_home OR
athlete_in_team.id_team = game.id_team_away OR
athlete_in_game.id_game = game.id
LEFT JOIN "sport_competition" ON sport_competition.id_game = game.id
GROUP BY "athlete"."id"
I need to choose all athletes which played in competitions. But it could be that no data in table "athlete_in_game" for several games and in this case I take all athletes from table "athlete_in_team" for these games. Because of it I use double "OR" in the third left join. I need all written conditions but because of double "OR" it could work too long. Is the chance to optimize it anyway?
i think first you have to improve schema in first place . team related info should be separate table. and game should be separate . you don't have to do left join with game table i think . only left join on athlete_in_game and athlete_in_team would be enough. like So
SELECT
"athlete"."id" AS "athlete_id"
FROM "athlete"
LEFT JOIN "athlete_in_game" ON athlete.id = athlete_in_game.id_athlete
LEFT JOIN "athlete_in_team" ON athlete.id = athlete_in_team.id_athlete
JOIN "game" ON
athlete_in_team.id_team = game.id_team_home OR
athlete_in_team.id_team = game.id_team_away OR
athlete_in_game.id_game = game.id
LEFT JOIN "sport_competition" ON sport_competition.id_game = game.id
GROUP BY "athlete"."id"

SQL query for finding Foreign key constraints

I have one column , and i want to find in How many table that column used as foreign and also name of the table in which that column is used. I have PostgreSQL database . and i am using PG admin tool
select R.TABLE_NAME from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE u
inner join INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS FK
on U.CONSTRAINT_CATALOG = FK.UNIQUE_CONSTRAINT_CATALOG
and U.CONSTRAINT_SCHEMA = FK.UNIQUE_CONSTRAINT_SCHEMA
and U.CONSTRAINT_NAME = FK.UNIQUE_CONSTRAINT_NAME inner join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE R
ON R.CONSTRAINT_CATALOG = FK.CONSTRAINT_CATALOG
AND R.CONSTRAINT_SCHEMA = FK.CONSTRAINT_SCHEMA
AND R.CONSTRAINT_NAME = FK.CONSTRAINT_NAME WHERE U.COLUMN_NAME='M_InLine_ID'
AND U.TABLE_NAME = 'M_InLine'
I tried above query but it snot given any output
Please help me out

Cannot get view to work on SQL Server

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