Unknown Column Left Join MySQL - mysql

I've used the "NOT IN (select)" Function, but it takes too long to load on several registers. So I want to improve the query using LEFT JOIN, but I don't know what's wrong. I'm getting #1054 - Unknown column 'a.id_logistica' in 'on clause'.
The column "id_logistica" in table "logistica" does exists, as it does in "det_log" table. This is the code:
SELECT
a.*, a.id_logistica,
b.nombre username, c.placa,
b.nombre scliente, e.nombre ruta,
d.nombre_con, clase
FROM
logistica a, cliente b,
vehiculo c, conductores d, ruta e
LEFT OUTER JOIN
det_log t2 ON t2.id_logistica = a.id_logistica
WHERE
a.id_cliente = b.id_cliente AND a.id_ruta = e.id_ruta
AND t2.id_logistica IS NULL AND a.id_vehiculo = c.id_vehiculo
AND a.id_conductor = d.id_conductor AND activo = 1
and finalizado = 0 AND ( a.id_ruta > 1 OR a.borrado = 9 )
ORDER BY
fecha_des DESC

if your query was running, you can try this one :
SELECT
a.*, a.id_logistica,
b.nombre username, c.placa,
b.nombre scliente, e.nombre ruta,
d.nombre_con, clase
FROM logistica a
Left Join cliente b On b.id_cliente = a.id_cliente
Left Join vehiculo c On c.id_vehiculo = a.id_vehiculo
Left Join conductores d On d.id_conductor = a.id_conductor
Left Join ruta e On e.id_ruta = a.id_ruta
Left Join det_log t2 On t2.id_logistica = a.id_logistica
WHERE ( a.id_ruta > 1 OR a.borrado = 9 )
And activo = 1
And finalizado = 0
And t2.id_logistica IS NULL
ORDER BY fecha_des DESC
but, if i look the error. it's mean nothing column "id_logistica" in table "logistica".
please check column in table "logistica".
desc logistica;
maybe, you wrong to write.

Related

Query to get all rows grouped by a field value with a condition on another field

I have following query:
SELECT
a.id_posicion,
a.profesional,
MAX( a.fecha_hora ) AS fechaPosicion,
a.latitud,
a.longitud,
b.tipo_profesional,
b.nombre,
b.apellidos,
c.tipo_profesional as tipoProfesional,
b.profile_image,
b.tel as tel,
e.especialidad as especialidad_profesional,
b.ciudad as ciudad,
b.departamento as departamento,
b.id_firebase as id_firebase
FROM tb_ultima_posicion_pro a
INNER JOIN users b ON b.id = a.profesional
INNER JOIN tb_profesionales c ON c.id_profesionales = b.tipo_profesional
INNER JOIN tb_especialidades_profesional d ON d.profesional = b.id
INNER JOIN tb_especialidades e ON d.especialidad = e.id_especialidad
GROUP BY a.profesional
ORDER BY fechaPosicion DESC
What I need is to get all records from the table tb_ultima_posicion_pro, grouped by the field profesional, which means that I get only a row for each profesional (that is ok), and for each profesional I need to get te row with the newest field fecha_hora, which is a datetime field.
What I am getting with this query is a row for each profesional (ok) but not the one with the newest fecha_hora field value.
Alternatively, You can first fetch the maximum fetch_hora by grouping the table tb_ultima_posicion_pro and then can join other tables -
SELECT a.id_posicion
,a.profesional
,am.fecha_hora AS fechaPosicion
,a.latitud
,a.longitud
,b.tipo_profesional
,b.nombre
,b.apellidos
,c.tipo_profesional as tipoProfesional
,b.profile_image
,b.tel as tel
,e.especialidad as especialidad_profesional
,b.ciudad as ciudad
,b.departamento as departamento
,b.id_firebase as id_firebase
FROM tb_ultima_posicion_pro a
INNER JOIN (SELECT profesional
,MAX(fecha_hora) AS fecha_hora
FROM tb_ultima_posicion_pro
GROUP BY profesional) am ON a.profesional = am.profesional
AND a.fecha_hora = am.fecha_hora
INNER JOIN users b ON b.id = a.profesional
INNER JOIN tb_profesionales c ON c.id_profesionales = b.tipo_profesional
INNER JOIN tb_especialidades_profesional d ON d.profesional = b.id
INNER JOIN tb_especialidades e ON d.especialidad = e.id_especialidad
ORDER BY fechaPosicion DESC

Unknown column in on clause - in query converted from SQL to HQL

I'm using Hibernate 4.3.11 and MySQL 5.7.11.
I wanted to rewrite this MySQL query to HQL:
SELECT COALESCE(g1.id, g2.id) as id, COALESCE(g1.type, g2.type) as type, COALESCE(g1.email_id, g2.email_id) as email_id, COALESCE(g1.url_id, g2.url_id) as url_id FROM notifications n
LEFT JOIN emails ON emails.id = n.email_id
LEFT JOIN urls ON urls.id = n.url_id
LEFT JOIN notifications_group g1 ON g1.email_id = n.email_id
LEFT JOIN notifications_group g2 ON g2.url_id = n.url_id
WHERE (((n.type = 'EMAIL' OR n.type = 'REMINDER') AND n.email_id is not null AND emails.user_id = :userId)
OR (n.type = 'URL' AND n.url_id is not null AND urls.user_id = :userId))
AND (g1.id is not null OR g2.id is not null)
AND ((g1.id is not null AND g1.id < :beforeId) OR (g2.id is not null AND g2.id < :beforeId))
GROUP BY COALESCE(g1.id, g2.id)
ORDER BY MAX(n.id) DESC
I have rewritten this native query to HQL:
SELECT COALESCE(g1.id, g2.id), COALESCE(g1.type, g2.type), COALESCE(g1.email, g2.email), COALESCE(g1.url, g2.url) FROM Notification n
LEFT JOIN n.email e
LEFT JOIN n.url u
LEFT JOIN e.notificationGroup g1
LEFT JOIN u.notificationGroup g2
WHERE (((n.type = delimail.enums.NotificationType.EMAIL OR n.type = delimail.enums.NotificationType.REMINDER) AND e IS NOT NULL AND e.user = :user)
OR (n.type = delimail.enums.NotificationType.URL AND u IS NOT NULL AND u.user = :user))
AND (g1 IS NOT NULL OR g2 IS NOT NULL)
AND ((g1.id IS NOT NULL AND g1.id < :beforeId) OR (g2 IS NOT NULL AND g2.id < :beforeId))
GROUP BY COALESCE(g1.id, g2.id), COALESCE(g1.type, g2.type), COALESCE(g1.email, g2.email), COALESCE(g1.url, g2.url)
ORDER BY MAX(n.id)
But it don't work. Hibernate generates this query:
SELECT coalesce(notificati3_.id, notificati4_.id) AS col_0_0_,
coalesce(notificati3_.type, notificati4_.type) AS col_1_0_,
coalesce(notificati3_.email_id, notificati4_.email_id) AS col_2_0_,
coalesce(notificati3_.url_id, notificati4_.url_id) AS col_3_0_
FROM delimail.notifications notificati0_
LEFT OUTER JOIN delimail.emails email1_ ON notificati0_.email_id=email1_.id
LEFT OUTER JOIN delimail.notifications_group notificati3_ ON email1_.id=notificati3_.email_id,
delimail.emails email5_, --l 8
delimail.urls url7_ --l 9
LEFT OUTER JOIN delimail.urls url2_ ON notificati0_.url_id=url2_.id --error: Unknown column 'notificati0_.url_id' in 'on clause'
LEFT OUTER JOIN delimail.notifications_group notificati4_ ON url2_.id=notificati4_.url_id,
delimail.emails email6_, --l 12
delimail.urls url8_ --l 13
WHERE notificati3_.email_id=email5_.id --l 14
AND notificati3_.url_id=url7_.id --l 15
AND notificati4_.email_id=email6_.id --l 16
AND notificati4_.url_id=url8_.id --l 17
AND ((notificati0_.type='EMAIL'
OR notificati0_.type='REMINDER')
AND (email1_.id IS NOT NULL)
AND email1_.user_id=?
OR notificati0_.type='URL'
AND (url2_.id IS NOT NULL)
AND url2_.user_id=?)
AND (notificati3_.id IS NOT NULL
OR notificati4_.id IS NOT NULL)
AND ((notificati3_.id IS NOT NULL)
AND notificati3_.id<?
OR (notificati4_.id IS NOT NULL)
AND notificati4_.id<?)
GROUP BY coalesce(notificati3_.id, notificati4_.id),
coalesce(notificati3_.type, notificati4_.type),
coalesce(notificati3_.email_id, notificati4_.email_id),
coalesce(notificati3_.url_id, notificati4_.url_id)
ORDER BY MAX(notificati0_.id)
And the error is:
Unknown column 'notificati0_.url_id' in 'on clause'
SQL Warning Code: 1054, SQLState: 42S22
But this query works as expected after removing marked lines 8-9, 12-13, and removing conditions in lines 14-17.
How can I convert this query to HQL? If it's possible.
I guess in this case since the query is kind of complex, You can very well go for native Query
Please see sample below:
String q="select employee_name from employee";
Query query= em.createNativeQuery(q,Object[].class);
List<Object[]> students= query.getResultList();
Please refer to the documentation below :
http://docs.oracle.com/javaee/7/api/javax/persistence/EntityManager.html#createNativeQuery-java.lang.String-

Unknown field on INNER JOIN from multi databases

I have following sql statement:
INSERT INTO wk1_tbl (shohin_code, shohin_mei, variation_flag)
SELECT ha.HINCD, ha.HINNMA, if (g.goods_para_id IS NULL, 0, 1) AS variation
FROM ( SELECT KOSHINCD, count(HINCD) AS quatity
FROM sc.HINMTF
GROUP BY KOSHINCD ) AS group_set
INNER JOIN sc.HINMTA ha
ON ha.HINCD = group_set.KOSHINCD
INNER JOIN master_hankoya.goods g
ON ha.WEBHINID = g.goods_id 
WHERE ha.HINKB = '2' and ha.DATKB <> '9';
I using INNER JOIN on multi-database ,so that you can see sc and master_hankoya is difference databases
When I run it ,I get error :
Unknown column 'g.goods_id ' in 'on clause'
You can see g alias for table master_hankoya.goods,and goods_id is a column in this
I guess that I have problem with INNER JOIN
Please help me correct it
Update : I check again and take a silly problem ,have a special character in query make it failed to run
try this
INSERT INTO wk1_tbl (shohin_code, shohin_mei, variation_flag)
SELECT ha.HINCD, ha.HINNMA, if (g.goods_para_id IS NULL, 0, 1) AS variation
FROM ( SELECT KOSHINCD, count(HINCD) AS quatity
FROM sc.HINMTF
GROUP BY KOSHINCD ) AS group_set
INNER JOIN sc.HINMTA ha
ON ha.HINCD = group_set.KOSHINCD
INNER JOIN
(select * from master_hankoya.goods ) g
ON ha.WEBHINID = g.goods_id
WHERE ha.HINKB = '2' and ha.DATKB <> '9';
Don't use alias name for master_hankoya.goods like
INSERT INTO wk1_tbl (shohin_code, shohin_mei, variation_flag)
SELECT ha.HINCD, ha.HINNMA, if (master_hankoya.goods.goods_para_id IS NULL, 0, 1) AS variation
FROM ( SELECT KOSHINCD, count(HINCD) AS quatity
FROM sc.HINMTF
GROUP BY KOSHINCD ) AS group_set
INNER JOIN sc.HINMTA ha
ON ha.HINCD = group_set.KOSHINCD
INNER JOIN master_hankoya.goods
ON ha.WEBHINID = master_hankoya.goods.goods_id
WHERE ha.HINKB = '2' and ha.DATKB <> '9';
INNER JOIN sc.HINMTA ha
Change this line to:
INNER JOIN HINMTA AS ha
INNER JOIN master_hankoya.goods g
Change that line to
INNER JOIN goods AS g
The syntax for setting an alias for a table is:
table_name AS table_alias

subquery value outside the scope

SELECT IFNULL(oea.`name`,op.name) AS "Consultation"
FROM `a` ca
JOIN `b` oea ON ca.`consultation_id` = oea.id AND oea.status = 1
LEFT OUTER JOIN c oeal ON oea.`location_id` = oeal.id
WHERE oea.employee_profile_id IN (
SELECT profile_id
FROM d pp
WHERE pp.status='1'
UNION
SELECT op.id
FROM e op
WHERE op.status
) AND
ca.status = 1
I am getting this error
Unknown column 'op.name' in 'field list'
Is there any possibility to use op.name outside the scope?
JOIN the subquery in the WHERE clause instead of using the IN predicate. This way you can select the name from it.
But you didn't select the column name from in the subquery. You selected only the profile_id, you have to select it with the profile_id. Something like:
SELECT
IFNULL(oea.`name`, op.name) AS Consultation
FROM `a` ca
JOIN `b` oea ON ca.`consultation_id` = oea.id AND oea.status = 1
INNER JOIN
(
SELECT profile_id, name
FROM d pp
WHERE pp.status='1'
UNION
SELECT op.id, name
FROM e op
WHERE op.status
) AS op ON oea.employee_profile_id = op.profile_id
LEFT OUTER JOIN c oeal ON oea.`location_id` = oeal.id
WHERE ca.status = 1;
I assumed that the two tables have the name column, if one of them didn't have it, you have to use null instead.

Some INNER JOIN in MySQL query

I have the next MySQL tables:
|provincias|
| id | |provincia|
|municipios|
| provincia_id| | id | |municipio|
|**event**|
|municipio_id|
|idEvent|
|name|
|date_begin|
|date_end|
I do the next MySQL query (EDITED):
SELECT idEvent, name
FROM evento e
INNER JOIN provincias p ON p.id = m.provincia_id
INNER JOIN municipios m ON m.id = e.municipio_id
WHERE provincia = "Iruña de Oka" AND municipio = "Álava"
AND DATE(date_begin) BETWEEN DATE('2013-07-23') AND DATE('2013-07-26')
ORDER BY name;
But I obtain the next error (EDITED):
1054 - Unknown column 'm.provincia_id' in 'on clause'
Join statements go before the WHERE clause
SELECT idEvent, name
FROM event e
INNER JOIN municipio m ON m.id = e.municipio_id
INNER JOIN provincia p ON p.id = m.provincia_id
WHERE provincial = "Iruña de Oka" AND municipio = "Álava"
AND DATE(date_begin) BETWEEN DATE('2013-07-23') AND DATE('2013-07-26')
ORDER BY name;
(And you were mixing non-ANSI and ANSI join syntax, which I've edited to use just the ANSI form)
In the from clause, a table cannot be referenced until it is defined. You are using m in the first on clause, before the definition.
The simple solution is to rearrange the clauses:
SELECT idEvent, name
FROM evento e
INNER JOIN municipios m ON m.id = e.municipio_id
INNER JOIN provincias p ON p.id = m.provincia_id
WHERE provincia = "Iruña de Oka" AND municipio = "Álava"
AND DATE(date_begin) BETWEEN DATE('2013-07-23') AND DATE('2013-07-26')
ORDER BY name;