Some INNER JOIN in MySQL query - mysql

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;

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

MySQL Subquery Optimization with shared subquery

From these tables I have written this subquery and its giving results as per requirements.
Needs expert guidence to improve this query or if we can also be able to use join for these tables.
Query:
select ps,st from pac where con in (select
config from config where logi in
( select id from logicalnode where physi
in (select id from ysicalnode where mas =11)));
SELECT
payloadstr
,starttime
FROM packetdb.packet
INNER JOIN packetdb.configuration
ON packetdb.packet.configid = packetdb.configuration.idconfig
INNER JOIN packetdb.logicalnode
ON packetdb.configuration.idconfig = packetdb.logicalnode.id
INNER JOIN packetdb.physicalnode
ON packetdb.logicalnode.physicalnodeid = packetdb.physicalnode.id and packetdb.physicalnode.macaddress=117769729
You could try using exists:
select payloadstr,starttime from packetdb.packet p
where exists(select 1 from packetdb.configuration c
where p.configid = id
and exists(select 1 from packetdb.logicalnode l
where c.logicalnodeid = id
and exists(select 1 from packetdb.physicalnode
where macaddress = 117769729
and l.physicalnodeid = id)
Using Left join
select payloadstr,starttime
from packet
left join Configuration on Configuration.IDconfig = packet.configID
left join logicalnode on logicalnode.ID = Configuration.logicalnodeid
left join physicalnode on physicalnode.ID = logicalnode.physicalnodeid
where macaddress =117769729
You can try below - using JOIN
select payloadstr,starttime
from packetdb.packet a inner join packetdb.configuration b on a.configid=b.idconfig
inner join packetdb.logicalnode c on logicalnodeid=c.id
inner join packetdb.physicalnode d on physicalnodeid=d.id
where macaddress =117769729
Try this
select pa,sta
from
pack p
INNER JOIN
confi c
ON
p.confi = c.idco
INNER JOIN
logice l
ON
c.logic = l.id
INNER JOIN
physiode pn
ON
l.physicalnodeid = pn.id
WHERE macaddress =123

Join two SQL tables from diferent queries

I'm trying to join these two queries. Can anyone help?
Query 1 -
SELECT provas.id, disciplinas.disciplina, disciplinas.grupo,salas.sala
FROM provas, disciplinas, horarios, salas
WHERE provas.id = provas.id AND provas.id_disciplina = disciplinas.id AND provas.id_horario = horarios.id AND provas.id_sala = salas.id AND provas.id_horario JOIN horarios ON ;
Query 2 -
SELECT dias.dia, meses.nome, horas.hora, minutos.minuto
FROM horarios, meses, dias, horas, minutos
WHERE horarios.id = horarios.id AND horarios.id_dia = dias.id AND horarios.id_hora = horas.id AND horarios.id_mes = meses.id AND horarios.id_minuto = minutos.id;
Main table
Second Main table
I want to associate the "provas" table with the "horario" but the horario table has more foreign keys
provas = exams
horarios = scheudule
I want to join the shedule on the exams table, but the sheudule have more foreign keys for tables "days", "months", "hours" and "minutes"
All involved tables
You can try the following query. I didn't run this to make sure no syntax errors. But you can see the concept. You can join with a result set of a second query as shown below. I suggest you to consider the joins in your original query again. You may change the joins in my answer as it fits for your purpose.
SELECT ps.id, das.disciplina, das.grupo,s.sala
FROM provas ps
inner join disciplinas das on ps.id_disciplina = das.id
inner join horarios hs on ps.id_horario = hs.id
inner join salas s on ps.id_sala = s.id
inner join (
SELECT d.dia, ms.nome, h.hora, m.minuto, hs.id hsid
FROM horarios hs
inner join meses ms on hs.id_mes = ms.id
inner join dias d on hs.id_dia = d.id
inner join horas h on hs.id_hora = h.id
inner join minutos m on hs.id_minuto = m.id) zz on ps.id_horario = zz.hsid
My solution (I prefer this way):
SELECT provas.id, disciplinas.disciplina, disciplinas.grupo,salas.sala ,dias.dia, meses.nome, horas.hora, minutos.minuto
FROM provas, disciplinas, horarios, salas, meses, dias, horas, minutos
WHERE provas.id = provas.id AND provas.id_disciplina = disciplinas.id AND provas.id_horario = horarios.id AND provas.id_sala = salas.id AND provas.id_horario AND horarios.id_dia = dias.id AND horarios.id_hora = horas.id AND horarios.id_mes = meses.id AND horarios.id_minuto = minutos.id;

Unknown Column Left Join 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.

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.