Joining third table in SQL - mysql

In the below query, I am trying to SELECT Destination_City.Name_, and to do so need to join Destination_City.Destination_City_ID with Contract_Items.Destination_City_ID, however the latter table is already inner joined with the Contract table.
SELECT
contract.Description,
---Destination_City.Name_,
contract_type.type AS 'Contract Type',
contract.Tour_Summary AS 'Tour Name',
employee.First_Name AS 'First Name',
employee.Last_name AS 'Last Name',
Currency_.Currency_Name AS 'Currency',
contract_Items.twin AS 'Twin Rate',
contract_items.Item_Rate AS 'Rate'
FROM
Contract
INNER JOIN Employee
ON Contract.Contracted_By_Employee_Id = Employee.Employee_Id
INNER JOIN Contract_Items
ON Contract.Contract_ID = Contract_Items.Contract_ID
INNER JOIN Currency_
ON Contract.Currency_Id = Currency_.Currency_Id
INNER JOIN Contract_Type
ON Contract.Contract_Type_Id = contract_type.Contract_Type_Id
Essentially Table 2 needs to be joined to Table 3, but Table 2 is already joined to Table 1. I have tried a couple of different approaches but both have thrown errors, and I am not sure how to write up this query.

It should be no problem to get your Name_ column with joining the DESTINATION_CITY table:
SELECT
contract.Description,
Destination_City.Name_,
contract_type.type AS 'Contract Type',
contract.Tour_Summary AS 'Tour Name',
employee.First_Name AS 'First Name',
employee.Last_name AS 'Last Name',
Currency_.Currency_Name AS 'Currency',
contract_Items.twin AS 'Twin Rate',
contract_items.Item_Rate AS 'Rate'
FROM
Contract
INNER JOIN Employee
ON Contract.Contracted_By_Employee_Id = Employee.Employee_Id
INNER JOIN Contract_Items
ON Contract.Contract_ID = Contract_Items.Contract_ID
INNER JOIN Currency_
ON Contract.Currency_Id = Currency_.Currency_Id
INNER JOIN Contract_Type
ON Contract.Contract_Type_Id = contract_type.Contract_Type_Id
INNER JOIN Destination_City
ON Destination_City.Destination_City_ID = Contract_Items.Destination_City_ID
Please note that the order of the join operations is irrelevant, if you have inner joins only. It's only required that one of the tables is already joined before.

this?
FROM Contract
INNER JOIN Employee
ON Contract.Contracted_By_Employee_Id = Employee.Employee_Id
INNER JOIN Contract_Items
ON Contract.Contract_ID = Contract_Items.Contract_ID
INNER JOIN Destination_City ON
Destination_City.Destination_City_ID = Contract_Items.Destination_City_ID
INNER JOIN Currency_
ON Contract.Currency_Id = Currency_.Currency_Id
INNER JOIN Contract_Type
ON Contract.Contract_Type_Id = contract_type.Contract_Type_Id

Related

Mysql subqueries problem with data retrieved

I'm trying to run a query but my outcome is not what i need.
So the problem is:
A user can be diretor and if this is the case he can see all activities from his department, and he can be user of another department too, in this case not director but only user.
I have 8 departments each with one director, so the following query should give me the activities of the department and the activities of this particular user in other department:
SELECT t1.idAtividade,
t1.idProfessor,
t2.Escola,
t1.Atividade,
t1.Periodo,
t1.Mes,
t1.haveClasses,
t1.DataPrevista,
t1.Destinatarios,
t1.Orcamento,
t1.PdfAtividade,
t1.Avaliacao,
t1.PdfAvaliacao,
t1.idProfessor,
p.Nome,
g.Grupo,
d.Departamento,
p2.Projeto,
t1.idProjeto
FROM atividades AS t1
INNER JOIN professores p on t1.idProfessor = p.idProfessor
INNER JOIN atividadesgrupos ag on t1.idAtividade = ag.idAtividade
INNER JOIN grupos g on ag.idGrupo = g.idGrupo
INNER JOIN departamentosatividades da on t1.idAtividade = da.idAtividade
INNER JOIN departamentos d on da.idDepartamento = d.idDepartamento
INNER JOIN escolas AS t2 ON (t2.idEscola = t1.idEscola)
INNER JOIN anosescolares AS ae ON (t1.idAnoEscolar = ae.idAnoEscolar)
INNER JOIN projetos p2 on t1.idProjeto = p2.idProjeto
WHERE ae.Estado = 1 AND (da.idDepartamento = :id_dpt and ag.idGrupo = :idGrupo)
ORDER BY (t1.idProfessor = :idProfessor) DESC, t1.idProfessor;");
This query is not working because the department have 22 activities but this user (idProfessor) has 5 in this department and 14 more in another department (defined by idGrupo)
I think i will need a subquery right?

How to update field values with values from another table

I have four tables by the name candidate, program_type, program_of_interest and desired_intake. The table candidate has a many to one relationship with the rest of the three tables.
The candidate table looks like this:
The program_type table:
The program_of_interest table:
The desired_intake table:
I am trying to replace the program_type,program_of_interest,desired_intake id's in the candidate table with the corresponding values in their respective tables.
I am able to select the values as needed with help from this thread SQL Replace multiple variables from another table in query result. Here is my solution to select:
SELECT
c.id,
p.value as 'Program type',
p1.value as 'Program of interest',
d.value as 'Desired intake'
FROM candidate c
JOIN program_type p on p.id = c.program_type
JOIN program_of_interest p1 on p1.id = c.program_of_interest
JOIN desired_intake d on d.id = c.desired_intake
My question is how do I replace the ids in the candidate table with their respective values?
You could use an update basend on join as
Update candidate c
INNER JOIN program_type p on p.id = c.program_type
INNER JOIN program_of_interest p1 on p1.id = c.program_of_interest
INNER JOIN desired_intake d on d.id = c.desired_intake
set c.program_type = p.value,
c.program_of_interest = p1.value,
c.desired_intake = d.value
but seems strange you want update eg: program_type with the value (c.program_type = p.value)
and you are using program_type for join ( p.id = c.program_type)

inner join in Sql Subquery

I am trying to run this query with using subquery but not able to fetch my result .is any one here to help me in geting it correct.
SELECT u.uv_id ID
, d.sd_code Code
, u.uv_name Title
, u.uv_nirf Nirf
, (SELECT sd_code
FROM vm_university_type t
JOIN vm_seo_detail d
ON t.ut_id = d.sd_ty_id
AND d.sd_ty = 'vm_university_type') AS 'University Type'
, a.ab_name 'Approved By'
, u.uv_seats Seats
, g.ug_name 'University Group'
FROM vm_universities u
JOIN vm_seo_detail d
ON u.uv_id = d.sd_ty_id
AND d.sd_ty = 'vm_universities'
JOIN vm_university_type t
ON u.uv_ut_id = t.ut_id
JOIN vm_approved_by a
ON u.uv_ab_id = a.ab_id
JOIN vm_caste c
ON u.uv_c_id = c.caste_id
JOIN vm_university_groups g
ON u.uv_ug_ids = g.ug_id;
i got this error Subquery returns more than 1 row
(SELECT `sd_code` FROM vm_university_type INNER JOIN vm_seo_detail ON (vm_university_type.ut_id = vm_seo_detail.sd_ty_id AND vm_seo_detail.sd_ty = 'vm_university_type') WHERE vm_university_type.ut_id=vm_universities.uv_ut_id ) AS 'University Type' ,
You do not need subquery at all. The column Code in SELECT statement contains University Type
Try below query.
SELECT vm_universities.uv_id AS 'ID' , vm_seo_detail.sd_code AS 'Code',
vm_universities.uv_name AS 'Title' , vm_universities.uv_nirf AS 'Nirf',
vm_approved_by.ab_name AS 'Approved By' , vm_universities.uv_seats as 'Seats',
vm_university_groups.ug_name AS 'University Group'
FROM vm_universities INNER JOIN vm_seo_detail
ON (vm_universities.uv_id = vm_seo_detail.sd_ty_id
AND vm_seo_detail.sd_ty = 'vm_universities')
INNER JOIN vm_university_type
ON (vm_universities.uv_ut_id = vm_university_type.ut_id)
INNER JOIN vm_approved_by
ON (vm_universities.uv_ab_id = vm_approved_by.ab_id)
INNER JOIN vm_caste
ON (vm_universities.uv_c_id = vm_caste.caste_id)
INNER JOIN vm_university_groups
ON (vm_universities.uv_ug_ids = vm_university_groups.ug_id);
SELECT `sd_code` FROM vm_university_type INNER JOIN vm_seo_detail ON (vm_university_type.ut_id = vm_seo_detail.sd_ty_id AND vm_seo_detail.sd_ty = 'vm_university_type')
looks like you forgot WHERE section in subquery, that will bind it to main query. something like
WHERE vm_university_type.ut_id=vm_universities.uv_ut_id
ps. and why you need this subquery at all, if you already join with vm_university_type in main query?

How to use same field from a table twice in one query

I have two tables: calls and employees. In the calls tables I have a field enter_emp_id and another follow_emp_id. They hold the values for which employee entered the call and which employee is assigned to the call. My second table employees has employee_id and employee fields. I am able to write a query to show results with an employee name for who entered the call, but not who it is assigned to. I do have other values in the query, but I need to get the 2nd employee name to show in the results. Here is what I am using so far:
SELECT
`calls`.`call_id`,
`calls`.`enter_date`,
`call_state`.`call_state`,
`customers`.`customer_name`,
`calls`.`comments`,
`employees`.`employee`,
`call_reasons`.`call_reason`
FROM
`customers`
INNER JOIN `calls` ON (`customers`.`customer_id` = `calls`.`customer_id`)
INNER JOIN `employees` ON (`employees`.`employee_id` = `calls`.`enter_emp_id`)
INNER JOIN `call_state` ON (`call_state`.`call_state_id` = `calls`.`call_state_id`)
INNER JOIN `call_reasons` ON (`call_reasons`.`call_reason_id` = `calls`.`call_reason_id`)
WHERE
`calls`.`call_id` = $call_id;
You need to join to the employee table TWICE... once for each employee id association, and use the ALIAS of the respective to get the values intended. And aliasing the tables and removal of unnecessary tick marks not required. Only needed for possible reserved word conflicts.
SELECT
c.call_id,
c.enter_date,
cs.call_state,
cust.customer_name,
c.comments,
entered.employee,
assigned.employee as AssignedEmployee,
cr.call_reason
FROM
calls c
INNER JOIN customers cust
ON c.customer_id = cust.customer_id
INNER JOIN employees entered
ON c.enter_emp_id = entered.employee_id
INNER JOIN employees assigned
ON c.enter_emp_id = assigned.employee_id
INNER JOIN call_state cs
ON c.call_state_id = cs.call_state_id
INNER JOIN call_reasons cr
ON c.call_reason_id = cr.call_reason_id
WHERE
c.call_id = $call_id;
I hope i understand you problem. You can use AS to change or shorten table name for sql usage
SELECT
`calls`.`call_id`,
`calls`.`enter_date`,
`call_state`.`call_state`,
`customers`.`customer_name`,
`calls`.`comments`,
`employees`.`employee`,
`assigned`.`employee` as assigned_employee,
`call_reasons`.`call_reason`
FROM
`customers`
INNER JOIN `calls` ON (`customers`.`customer_id` = `calls`.`customer_id`)
INNER JOIN `employees` ON (`employees`.`employee_id` = `calls`.`enter_emp_id`)
INNER JOIN `employees` AS `assigned` ON (`assigned`.`employee_id` = `calls`.`follow_emp_id`)
INNER JOIN `call_state` ON (`call_state`.`call_state_id` = `calls`.`call_state_id`)
INNER JOIN `call_reasons` ON (`call_reasons`.`call_reason_id` = `calls`.`call_reason_id`)
WHERE
`calls`.`call_id` = $call_id;
Thanks the following worked:
SELECT
c.call_id,
c.enter_date,
cs.call_state,
cust.customer_name,
c.comments,
entered.employee,
entered.employee,
cr.call_reason
FROM
calls c
INNER JOIN customers cust
ON c.customer_id = cust.customer_id
INNER JOIN employees entered
ON c.enter_emp_id = entered.employee_id
INNER JOIN employees assigned
ON c.enter_emp_id = assigned.employee_id
INNER JOIN call_state cs
ON c.call_state_id = cs.call_state_id
INNER JOIN call_reasons cr
ON c.call_reason_id = cr.call_reason_id
WHERE
c.call_id = $call_id;

How to make SQL query from many tables on Rails?

Thank you for read my quetsion.
I want to know which is the best or correct way to express queries in Rails which make many joins and select attributes from multiple tables:
SELECT
ffca.name,
ffc.name,
ft.title,
concat(s.first_name, ' ', s.last_name),
pf.name,
ft.amount,
date_format(ft.created_at,'%d/%m/%y')
FROM
finance_transactions ft
INNER JOIN students s ON ft.student_id = s.id
INNER JOIN payment_forms pf ON ft.payment_form_id = pf.id
INNER JOIN finance_fees ff ON ft.finance_fees_id = ff.id
INNER JOIN finance_fee_collections ffc ON ff.fee_collection_id = ffc.id
INNER JOIN finance_fee_categories ffca ON ffc.fee_category_id = ffca.id;
If you need extra info, please feel free to ask me.
Thank you very much.
e.g
your model is finance_transactions
finace_transaction = FinanceTransaction.find_by_sql(
"SELECT
ffca.name as name,
ffc.name as name1,
ft.title as title,
concat(s.first_name, ' ', s.last_name) as full_name,
pf.name as pf_name,
ft.amount as count,
date_format(ft.created_at,'%d/%m/%y') as time
FROM
finance_transactions ft
INNER JOIN students s ON ft.student_id = s.id
INNER JOIN payment_forms pf ON ft.payment_form_id = pf.id
INNER JOIN finance_fees ff ON ft.finance_fees_id = ff.id
INNER JOIN finance_fee_collections ffc ON ff.fee_collection_id = ffc.id
INNER JOIN finance_fee_categories ffca ON ffc.fee_category_id = ffca.id"
)
the table finance_transactions table must have column name, name1,title, full_name,pf_name, count, time
and then you can use:
finace_transaction.name1 gets ffc.name
You might want to provide a method in your model class as a wrapper
class FinanceTransaction < ActiveRecord::Base
[...]
def self.find_fee_transactions
self.find_by_sql(<<-SQL)
SELECT
ffca.name as name,
ffc.name as name1,
ft.title as title,
concat(s.first_name, ' ', s.last_name) as full_name,
pf.name as pf_name,
ft.amount as count,
date_format(ft.created_at,'%d/%m/%y') as time
FROM
finance_transactions ft
INNER JOIN students s ON ft.student_id = s.id
INNER JOIN payment_forms pf ON ft.payment_form_id = pf.id
INNER JOIN finance_fees ff ON ft.finance_fees_id = ff.id
INNER JOIN finance_fee_collections ffc ON ff.fee_collection_id = ffc.id
INNER JOIN finance_fee_categories ffca ON ffc.fee_category_id = ffca.id"
)
SQL
end
end