I have a situation where a property table holds an address id (from the g_addresses table) and an applicant table also holds an address id from the g_addresses.
I'd like to left join these together but select all the fields in the table.
I know of using 'as' to make an alias for fields, but is there any way to produce an alias for a whole table?
SELECT *
FROM (`reference`)
LEFT JOIN `applicants` ON `applicants`.`id` = `reference`.`applicant_id`
LEFT JOIN `g_people` applicant_person ON `applicant_person`.`id` = `applicants`.`person_id`
LEFT JOIN `g_addresses` applicant_address ON `applicant_address`.`id` = `applicants`.`address_id`
LEFT JOIN `properties` ON `properties`.`id` = `reference`.`property_id`
LEFT JOIN `g_addresses` property_address ON `property_address`.`id` = `properties`.`address_id`
WHERE `reference`.`id` = 4
This produces a result containing only one address row and not both,
The row that is returned is the row from the final join and not the one previously, indicating it is overwriting when it is returned.
I don't think you should use masked references, like * or `reference`.*, in your case, because you may end up with a row set containing identical column names (id, address_id).
If you want to pull all the columns from the joined tables, you should probably specify them individually in the SELECT clause and assign a unique alias to every one of them:
SELECT
ref.`id` AS ref_id,
ref.`…` AS …,
…
app.`id` AS app_id,
…
FROM `reference` AS ref
LEFT JOIN `applicants` AS app ON app.`id` = ref.`applicant_id`
LEFT JOIN `g_people` AS ape ON ape.`id` = app.`person_id`
LEFT JOIN `g_addresses` AS apa ON apa.`id` = app.`address_id`
LEFT JOIN `properties` AS pro ON pro.`id` = ref.`property_id`
LEFT JOIN `g_addresses` AS pra ON pra.`id` = pro.`address_id`
WHERE ref.`id` = 4
Be more specific about columns you select
SELECT
applicant_address.*,
property_address.*,
applicants.*,
applicant_person.*,
properties.*
FROM (`reference`)
LEFT JOIN `applicants` ON `applicants`.`id` = `reference`.`applicant_id`
LEFT JOIN `g_people` applicant_person ON `applicant_person`.`id` = `applicants`.`person_id`
LEFT JOIN `g_addresses` applicant_address ON `applicant_address`.`id` = `applicants`.`address_id`
LEFT JOIN `properties` ON `properties`.`id` = `reference`.`property_id`
LEFT JOIN `g_addresses` property_address ON `property_address`.`id` = `properties`.`address_id`
WHERE `reference`.`id` = 4
Related
I have two tables
Table1: violations
Columns: date, time, pdid, pname, v1, v2, v3, v4
Each v1 through v4 has an integer value which corresponds to a single entry (ID) in table 2.
table2: parking_violations
columns: code, section, description, ID
I need to query each record of violations based on pdid, and match each 'v1-v4' to column 'ID' in the p_violations table.
SELECT
parking.date,
parking.time,
parking.pname,
parking_violations.code,
parking_violations.section,
parking_violations.description
FROM
parking
INNER JOIN parking_violations ON parking.v1=parking_violations.ID
WHERE
pdid=5
This returns the correct records for V1, but I cannot figure out how to also return V2-V4 all populated by matching the value to ID.
Like #fa06 explain, you can use multiple joins to the same table, but instead of inner join i will use left join, this way i have the flexibility of get rows where not all vN have matching IDs on the table parking_violations.
SELECT
parking.date,
parking.time,
parking.pname,
pv1.code,
pv1.section,
pv1.description,
pv2.code,
pv2.section,
pv2.description,
pv3.code,
pv3.section,
pv3.description,
pv4.code,
pv4.section,
pv4.description
FROM
parking
LEFT JOIN
parking_violations AS pv1 ON pv1.ID = parking.v1
LEFT JOIN
parking_violations AS pv2 ON pv2.ID = parking.v2
LEFT JOIN
parking_violations AS pv3 ON pv3.ID = parking.v3
LEFT JOIN
parking_violations AS pv4 ON pv4.ID = parking.v4
WHERE
parking.pdid = 5;
use join multiple time with alias like below:
SELECT
parking.date,
parking.time,
parking.pname,
parking_violations.code,
parking_violations.section,
parking_violations.description
FROM
parking
INNER JOIN parking_violations ON parking.v1=parking_violations.ID
inner join parking_violations a ON parking.v2=a.ID
inner join parking_violations b ON parking.v3=b.ID
inner join parking_violations c ON parking.v4=d.ID
WHERE
pdid=5
How can I access data from an outer table in a SELECT, and use it in an WHERE inside a JOIN estructure?
Below is the current query:
SELECT
cvl.id caracteristica_valor_id,
cvl.nome caracteristica_valor_nome,
cvl.valor caracteristica_valor_valor,
ctp.id caracteristica_tipo_id,
ctp.nome caracteristica_tipo_nome,
ctp.codigo caracteristica_tipo_codigo,
ctp.tipo caracteristica_tipo_tipo,
COUNT(DISTINCT var.id_perfil_produto) quantidade_itens
FROM
caracteristica_variacao cvr
INNER JOIN caracteristica_valor cvl ON cvl.id = cvr.id_caracteristica_valor
INNER JOIN caracteristica_tipo ctp ON ctp.id = cvl.id_caracteristica_tipo
INNER JOIN variacao var ON var.id = cvr.id_variacao
INNER JOIN(
SELECT DISTINCT
ppr.id perfil_produto_id
FROM
perfil_produto ppr
INNER JOIN produto pro ON pro.id = ppr.id_produto
INNER JOIN(
SELECT ppr2.id AS id_perfil_sub,a
COUNT(var.id) AS qtd_variacoes,
SUM(var.quantidade_estoque) AS quantidade_estoque,
COALESCE(SUM(var.quantidade_estoque_reservada),0) AS quantidade_estoque_reservada,
MIN(var.disponibilidade) AS disponibilidade,
MIN(var.frete_gratis) AS frete_gratis,
MIN(var.preco_venda) AS preco_venda,
MAX(var.preco_listagem) AS preco_listagem
FROM
variacao var
LEFT JOIN perfil_produto ppr2 ON ppr2.id = var.id_perfil_produto
LEFT JOIN caracteristica_variacao cvr_1 ON cvr_1.id_variacao = var.id
LEFT JOIN caracteristica_valor cvl_1 ON cvl_1.id = cvr_1.id_caracteristica_valor
LEFT JOIN caracteristica_tipo ctp_1 ON ctp_1.id = cvl_1.id_caracteristica_tipo
WHERE
var.disponibilidade = 1
AND(
ctp_1.codigo = 'tamanho' AND cvl_1.valor IN('p')
)
GROUP BY
ppr2.id
) AS grp_var ON grp_var.id_perfil_sub = ppr.id
INNER JOIN produto_categoria prc ON pro.id = prc.produto_id
INNER JOIN categoria cat ON prc.categoria_id = cat.id
WHERE
pro.disponibilidade = 1 AND prc.categoria_id IN (164, 165, 166)
) AS produto ON produto.perfil_produto_id = var.id_perfil_produto
GROUP BY
cvl.id
ORDER BY
ctp.tipo ASC,
ctp.id
I need the field ctp.codigo from the outer table inside thist part:
WHERE
var.disponibilidade = 1
AND(
ctp_1.codigo = 'tamanho' AND cvl_1.valor IN('p')
)
for this section to be as follows:
WHERE
var.disponibilidade = 1
AND(
(ctp.codigo != 'tamanho' AND ctp_1.codigo = 'tamanho' AND cvl_1.valor IN('p'))
OR
(ctp.codigo = 'tamanho')
)
It's not possible to reference columns from the outer query from inside an inline view query.
In the MySQL venacular, the inline view query is called a "derived table". And that name makes sense, because of the way MySQL processes it. The execution plan first materializes the inline view query into a temporary(-ish) table. Once that is done, then the outer query can run, referencing the contents of the derived table.
MySQL doesn't have available the columns from the outer query at the time the inline view query runs.
It is possible to reference columns from the outer query inside a subquery that appears for example in the SELECT list, or in the WHERE clause. We call a subquery that references columns from outer query a "correlated subquery".
In the picture is my table situation right now:
The central table in this case right now is tblJob, here is everything defined what I need (not all in the picture).
The address table needs to return 2 values (1 of the company and 1 of the job itself). The only thing I need to do right now is to add the company address (the job address is already in my query) My query already looks like this:
SELECT
tblJob.jobID,
tblJob.amount AS jobAmount,
tblJob.extraInfo AS jobExtraInfo,
tblJob.views AS jobViews,
tblJob.description AS jobDescription,
tblJob.dateCreated AS jobDateCreated,
tblJobFunction.jobFunctionID,
tblJobFunction.jobFunction,
tblAddress.zipcode AS jobAddress,
tblAddress.city AS jobCity,
tblAddress.street AS jobStreet,
tblAddress.number AS jobNumber,
tblAddress.bus AS jobBus,
tblCountry.countryID AS jobCountryID,
tblCountry.country AS jobCountry,
tblCountry.areaCode AS jobAreaCode,
tblCompany.companyID,
tblCompany.name,
tblCompany.email,
tblCompany.GSM,
tblCompany.phoneNumber,
tblCompany.photoURL AS companyPhotoURL,
tblCompany.VATNumber,
tblCompany.websiteURL,
tblEvent.eventID,
tblEvent.event,
tblEvent.description AS eventDescription,
tblEvent.startDate AS eventStartDate,
tblEvent.endDate AS eventEndDate,
tblEvent.facebookURL,
tblEvent.photoURL AS eventPhotoURL,
tblEvent.views AS eventViews,
tblEvent.dateCreated AS eventDateCreated
FROM tblJob
JOIN tblAddress ON tblAddress.addressID = tblJob.addressID
JOIN tblCountry ON tblAddress.countryID = tblCountry.countryID
JOIN tblJobFunction ON tblJob.jobFunctionID =
tblJobFunction.jobFunctionID
JOIN tblCompany ON tblJob.companyID = tblCompany.companyID
LEFT JOIN tblEvent ON tblJob.eventID = tblEvent.eventID
Now the question is: how can I add the address from the company in the same query?
Use the address table as many times as you need it, but each time you must give it a new alias:
FROM tblJob
JOIN tblAddress ON tblAddress.addressID = tblJob.addressID
JOIN tblCountry ON tblAddress.countryID = tblCountry.countryID
JOIN tblJobFunction ON tblJob.jobFunctionID = tblJobFunction.jobFunctionID
JOIN tblCompany ON tblJob.companyID = tblCompany.companyID
JOIN tblAddress a2 ON a2.addressID = tblCompany.addressID
LEFT JOIN tblEvent ON tblJob.eventID = tblEvent.eventID
perhaps more like this:
SELECT JobAddress.street, CompanyAddress.street
FROM tblJob
JOIN tblAddress JobAddress ON JobAddress.addressID = tblJob.addressID
JOIN tblCompany ON tblJob.companyID = tblCompany.companyID
JOIN tblAddress CompanyAddress ON CompanyAddress.addressID = tblCompany.addressID
SELECT
fromData.name as fromname, toData.name as toName, prodData.prodname,
t1.`from_id`, t1.`to_id` , t1.`product_id` , t1.`title`, t1.`message`, t1.`senttime` , t1.`readstatus`, t1.`responded`, t1.`merchanthidden`
FROM `inquiries` as t1
INNER JOIN users as fromData on t1.from_id = fromData.id
INNER JOIN users as toData on t1.to_id = toData.id
INNER JOIN products as prodData on t1.product_id = prodData.id
WHERE t1.id=13
Above query joins 3 tables (inquiries, users, products) together and gets data from each table.
Sometimes it is possible that items in the 'products' table get deleted. Trying to join products table by a deleted product id will fail the query.
Is there a way that I can assign 'prodData.prodname' a default value and execute query without failing in case of a missing item in products table ?
Why don't use left join insted of inner join ,
The LEFT JOIN keyword returns all records from the left table (table1), and the matched records from the right table (table2). The result is NULL from the right side, if there is no match.
SELECT
fromData.name as fromname, toData.name as toName, prodData.prodname,
t1.`from_id`, t1.`to_id` , t1.`product_id` , t1.`title`, t1.`message`, t1.`senttime` , t1.`readstatus`, t1.`responded`, t1.`merchanthidden`
FROM `inquiries` as t1
INNER JOIN users as fromData on t1.from_id = fromData.id
INNER JOIN users as toData on t1.to_id = toData.id
LEFT JOIN products as prodData on t1.product_id = prodData.id
WHERE t1.id=13
In mysql I'd like to do 2 unique LEFT JOINs on the same table cell.
I have two tables.
One table lists individual clients and has a clientNoteID and staffNoteID entry for each client. clientNoteID and staffNoteID are both integer references of a unique noteID for the note store in the notesTable.
clientsTable:
clientID | clientName | clientNoteID | staffNoteID
notesTable:
noteID | note
I'd like to be able to select out of the notesTable both the note referenced by the clientNoteID and the note referenced by the staffNoteID.
I don't see any way to alias a left join like:
SELECT FROM clientsTable clientsTable.clientID, clientsTable.clientName, clientsTable.clientNoteID, clientsTable.stylistNoteID
LEFT JOIN notes on clientTable.clientNotesID = notes.noteID
LEFT JOIN notes on clientTable.staffNoteID = notes.noteID as staffNote
(not that i think that really makes too much sense)
So, how could I query so that I can print out at the end:
clientName | clientNote | staffNote
When you join a table the alas must be immediately after the table name, not after the join condition. Try this instead:
SELECT clientsTable.clientName, n1.note AS clientNote, n2.note AS staffNote
FROM clientsTable
LEFT JOIN notes AS n1 ON clientTable.clientNotesID = n1.noteID
LEFT JOIN notes AS n2 ON clientTable.staffNoteID = n2.noteID
you need to alias the tables themselves
SELECT FROM clientsTable clientsTable.clientID, clientsTable.clientName, clientsTable.clientNoteID, clientsTable.stylistNoteID
LEFT JOIN notes a on clientTable.clientNotesID = a.noteID
LEFT JOIN notes b on clientTable.staffNoteID = b.noteID
SELECT CT.clientName, N1.note AS clientNote, N2.note AS staffNote
FROM clientsTable CT
LEFT JOIN notes N1 on CT.clientNotesID = N1.noteID
LEFT JOIN notes N2 on CT.staffNoteID = N2.noteID