MySQL inner join w/ alias - mysql

So this is my table DENUNCIAS
id_denuncia,
id_categoria,
id_fecha,
email_denunciante -- FK table usuarios,
email_denunciado -- FK table usuarios,
descripcion,
fecha
As you can see i have a double reference to the same table.
What i'm trying to do is select (inner join) 'usuarios.nombreCompleto' twice, once for 'email_denunciante' and the other for 'email_denunciado' . This is where i am so far:
select
categorias.nombreCorto as 'Categoria',
fechas.circuito as 'Fecha',
usuarios.nombreCompleto as usuDenunciante,
usuarios.nombreCompleto as usuDenunciado,
denuncias.descripcion as 'Detalle',
denuncias.fecha as 'Enviada el'
from denuncias
inner join categorias on denuncias.id_categoria = categorias.id_categoria
inner join fechas on denuncias.id_fecha = fechas.id_fecha
inner join usuarios as usuDenunciante on denuncias.email_denunciante = usuarios.email
inner join usuarios as usuDenunciado on denuncias.email_denunciado = usuarios.email;
And this is the error i get:
Error Code: 1054. Unknown column 'usuarios.nombreCompleto' in 'field list'
I'd tried several methods with negative results.
Since it's a sintaxis error, not logic, i decided not to translate the code.
Thanks in advance!

You create table alias, you must use then on your select list. usuarios must be usuDenunciante or usuDenunciado.
Try this:
select categorias.nombreCorto as 'Categoria',
fechas.circuito as 'Fecha',
usuDenunciante.nombreCompleto as usuDenunciante,
usuDenunciado.nombreCompleto as usuDenunciado,
denuncias.descripcion as 'Detalle',
denuncias.fecha as 'Enviada el'
from denuncias
inner join categorias
on denuncias.id_categoria = categorias.id_categoria
inner join fechas
on denuncias.id_fecha = fechas.id_fecha
inner join usuarios as usuDenunciante
on denuncias.email_denunciante = usuDenunciante.email
inner join usuarios as usuDenunciado
on denuncias.email_denunciado = usuDenunciado.email;

I'm assuming that your usarious table really do contain the nombreCompleto column. If this is correct, I think the problem is, that you reference the usarious table directly instead of using the aliases you have made. Because you access that table twice, you need to specify which alias you mean to SELECT from.
Fx:
SELECT categorias.nombreCorto as 'Categoria',
fechas.circuito as 'Fecha',
usuDenunciante.nombreCompleto.as usuDenunciante,
usuDenunciado.nombreCompleto as usuDenunciado,
denuncias.descripcion as 'Detalle',
denuncias.fecha as 'Enviada el'
from denuncias inner join categorias on denuncias.id_categoria = categorias.id_categoria
inner join fechas on denuncias.id_fecha = fechas.id_fecha
inner join usuarios as usuDenunciante on denuncias.email_denunciante = usuarios.email
inner join usuarios as usuDenunciado on denuncias.email_denunciado = usuarios.email;

Related

MySQL How can I use the result of a stored function as a paramater in the same SELECT statement

So my question is, how can i use the result of berekenKosten() as a parameter for nogTeBetalen() in the same SELECT statement? Here is my code:
SELECT boeking.Boekingnr, Naam, Telefoonnr, boeking.Aantal_volwassenen, reis.Prijs_per_persoon, boeking.Betaald_bedrag,
berekenKosten(reis.Prijs_per_persoon, boeking.Aantal_volwassenen) AS totaalprijs, nogTeBetalen()
FROM klant
INNER JOIN boeking ON klant.Klantnr = boeking.Klantnr
INNER JOIN reis ON boeking.Reisnr = reis.Reisnr
if this isn't possible, how can I display the result of nogTeBetalen() as a column for each row?
i already tried this, but it didn't work:
SELECT boeking.Boekingnr, Naam, Telefoonnr, boeking.Aantal_volwassenen, reis.Prijs_per_persoon, boeking.Betaald_bedrag,
berekenKosten(reis.Prijs_per_persoon, boeking.Aantal_volwassenen) AS totaalprijs, nogTeBetalen(totaalprijs)
FROM klant
INNER JOIN boeking ON klant.Klantnr = boeking.Klantnr
INNER JOIN reis ON boeking.Reisnr = reis.Reisnr
You can nest the calls:
SELECT
b.Boekingnr,
Naam,
Telefoonnr,
b.Aantal_volwassenen,
r.Prijs_per_persoon,
b.Betaald_bedrag,
berekenKosten(r.Prijs_per_persoon, b.Aantal_volwassenen) AS totaalprijs,
nogTeBetalen(berekenKosten(r.Prijs_per_persoon, b.Aantal_volwassenen)) as result
FROM klant k
INNER JOIN boeking b ON k.Klantnr = b.Klantnr
INNER JOIN reis r ON b.Reisnr = r.Reisnr
But it is probably more efficient to use a subquery, so the procedure is only invoked once:
SELECT t.*, nogTeBetalen(totaalprijs) as result
FROM (
SELECT
b.Boekingnr,
Naam,
Telefoonnr,
b.Aantal_volwassenen,
r.Prijs_per_persoon,
b.Betaald_bedrag,
berekenKosten(r.Prijs_per_persoon, b.Aantal_volwassenen) AS totaalprijs
FROM klant k
INNER JOIN boeking b ON k.Klantnr = b.Klantnr
INNER JOIN reis ON b.Reisnr = r.Reisnr
) t
Side recommendations:
use table aliases to shorten the query and increase its readability, as shown above
do prefix each and every columnm with the (alias of) the table it belongs to, so the query is umabiguous about the underlying data structures; there a a few unqualified columns in the SELECT clause that you would need to fix

MySQL Select and Join - Ambiguous column

I'm trying to join four tables together. The code works fine when I'm only comparing the EVENT_DATA and joining the PERSONA tables as I'm able to get the "Name" column from PERSONA (which doesn't exist in the EVENT_DATA table). However, one of the problems is that this "Name" column also exists in the CUSTOMCAR table, so I can only get one or the other. Additionally, when I tried adding the last join statement, the code wouldn't run at all.
If someone could please help me, that would be great!
$sql = "SELECT * FROM EVENT_DATA
LEFT JOIN PERSONA ON EVENT_DATA.personaId = PERSONA.ID
LEFT JOIN CUSTOMCAR ON CUSTOMCAR.ownedCarId = EVENT_DATA.carId
LEFT JOIN CARCLASSES ON CARCLASSES.store_name = CUSTOMCAR.name
WHERE (EVENT_DATA.EVENTID = '299')";
You should avoid * and use explicit columns list instead:
SELECT EVENT_DATA.personaId, ...
FROM EVENT_DATA
LEFT JOIN PERSONA ON EVENT_DATA.personaId = PERSONA.ID
LEFT JOIN CUSTOMCAR ON CUSTOMCAR.ownedCarId = EVENT_DATA.carId
LEFT JOIN CARCLASSES ON CARCLASSES.store_name = CUSTOMCAR.name
WHERE (EVENT_DATA.EVENTID = '299');
If you have same column name you need to to use aliasing:
SELECT ...
CUSTOMCAR.NAME AS c_name,
PERSONA.NAME AS p_name
...
You could also use Aliasing:
$sql = "SELECT ed.*,
pa.*,
cc.*,
ccs.*
FROM EVENT_DATA AS ed
LEFT JOIN PERSONA AS pa ON ed.personaId = pa.ID
LEFT JOIN CUSTOMCAR AS cc ON cc.ownedCarId = e.carId
LEFT JOIN CARCLASSES AS ccs ON ccs.store_name = cc.name
WHERE (ed.EVENTID = '299')";
Note: Although as suggested by #Lukasz, you should really avoid using wildcard (*), and provide an explicit list of columns in the SELECT clause.

You can't specify target table '...' for update in FROM clause

I want to make an update on a table with the results of a query and that records exist in the tables, my SLQ is:
UPDATE
reparticion
SET
responsable_nombre_completo = (select CONCAT_WS(',',persona.nombre,persona.apellido) FROM persona INNER JOIN usuario on usuario.cuil = persona.cuil)
WHERE
reparticion.id IN (select persona.reparticion_id FROM persona INNER JOIN usuario on usuario.cuil = persona.cuil INNER JOIN reparticion on reparticion.id = persona.reparticion_id);
but I get the following error:
You can't specify target table 'reparticion' for update in FROM clause
The better approach would be to use join update instead of sub-queries.
update reparticion r
join persona p on p.reparticion_id = r.id
join usuario u on u.cuil = p.cuil
set r.responsable_nombre_completo = CONCAT_WS(',',p.nombre,p.apellido)

Double query a table from two fields (INNER JOIN?)

I hope I can explain myself.
I have a many to many table (asignaciones) which points to alumnos and invest tables. Both of those tables has a institucionID which points to instituciones table.
I need to get (in one query) both instituciones from alumnos and invest. I have this but is not complete. I guess if because of the AND in the last inner join:
SELECT
alumnos.alumnosID,
invest.investigadoresID,
asignaciones.alumnosID AS alumnosID1,
asignaciones.investigadoresID AS investigadoresID1,
instituciones.institucion
FROM alumnos
INNER JOIN asignaciones ON alumnos.alumnosID = asignaciones.alumnosID
INNER JOIN invest ON asignaciones.investigadoresID = invest.investigadoresID
INNER JOIN instituciones ON alumnos.institucionesID = instituciones.institucionesID AND invest.institucionesID = instituciones.institucionesID
This lacks the second institucion. I am getting just one
Any hints on this is really appreciated
This Query schold solve your problem:
SELECT
alumnos.alumnosID,
invest.investigadoresID,
asignaciones.alumnosID AS alumnosID1,
asignaciones.investigadoresID AS investigadoresID1,
instituciones.institucion
instituciones1.institucion
FROM alumnos
INNER JOIN asignaciones ON alumnos.alumnosID = asignaciones.alumnosID
INNER JOIN invest ON asignaciones.investigadoresID = invest.investigadoresID
INNER JOIN instituciones instituciones ON alumnos.institucionesID = instituciones.institucionesID
INNER JOIN instituciones instituciones1 ON invest.institucionesID = instituciones1.institucionesID
You have to join the last table twice.

SQL query for returning multiple fields joined to the same reference

So I have the following table, do_stock_movement, that looks like this:
stock_movement_id sm_number sm_source_id sm_destination_id
15164b86a7533d 145 1516478840ee29 151644d8bd63f2
15166b89d1a9fc 194 15165c481bd9d0 151659e632cd48
The columns sm_source_id and sm_destination_id both reference product points stored in do_product_points.
I'm using the following SQL query:
SELECT * FROM do_stock_movement
INNER JOIN do_product_points ON product_points_id = sm_source_id
WHERE sm_number = '145'
In do_product_points, there's a field called pp_name. I need the corresponding pp_name for both sm_source_id and sm_destination_id.
However, the query above will only return the pp_name for sm_source_id, or for sm_destination_id if you change the joined field to that.
What SQL query will return the corresponding pp_name for both sm_source_id and sm_destination_id?
I hope this is clear. Please ask questions if it isn't!
JOIN this table do_product_points one more times for the sm_destination_id:
SELECT
s.pp_name AS SourcePoint,
d.pp_name AS DestinationPoint,
...
FROM do_stock_movement AS m
INNER JOIN do_product_points s ON s.product_points_id = m.sm_source_id
INNER JOIN do_product_points d ON d.product_points_id = m.sm_destination_id
WHERE m.sm_number = '145'
You need join twice and use alias:
SELECT *, Src.pp_name, Dst.pp_name FROM do_stock_movement
INNER JOIN do_product_points as Src
ON Src.product_points_id = sm_source_id
INNER JOIN do_product_points as Dst
ON Dst.product_points_id = sm_destination_id
You need to join to the product_points table twice, once with source_id and once with destination_id:
SELECT * FROM do_stock_movement move
INNER JOIN do_product_points source ON source.product_points_id = move.sm_source_id
INNER JOIN do_product_points dest ON dest.product_points_id = move.sm_destination_id
WHERE sm_number = '145'