Struggling with MySQL query - mysql

I have the following model:
I've been at this for a while and still don't know how to tackle it properly. Already looked at joining two aliased subqueries, joining two views, and tried a gynormous and ugly all-in one query, none of which worked.
My question is simple:
How can I select deivce_names.name and match them to a model and manufacturer?

SELECT
name, manufacturer, model
FROM
device_names
JOIN devices ON (device_names.id = name_id)
JOIN devices_generic ON (generic_device_id = devices_generic.id)
JOIN device_manufacturers ON (manufacturer_id = device_manufacturers.id)
JOIN device_models ON (model_id = device_models.id)

select
device_names.name as device_name,
device_manufacturers.name as device_manufacturer_name,
device_models.name as device_model_name
from deivce_names
join device on device.name_id = deivce_names.id
join devices_generic on devices_generic.id = devices.generic_device_id
join device_manufacturers on devices_generic.manufacturer_id = device_manufacturers.id
join device_models on device_models.id = devices_generic.model_id

SELECT dm1.manufacturer, dm2.model from device_manufacturers as dm1 join devices_generic as dg on dg.manufacturer_id = dm1.id join device_models as dm2 on dm2.id = dg.model_id join devices as d2 on d2.generic_device_id = dg.id join device_names as dn on dn.id = d2.name_id where name = 'foo'
In the future, you might want to simply put your data into a fiddle and play with it there.

Related

How to join many tables without duplicate result?

Hello all StackOverFlow families.
I need your help about sql query in mysql. I join four tables but result is duplicate row.
I have tried by using GROUP BY but not work.
Here is my query:
SELECT `tbl_leave`.`id`, `tbl_leave`.`staff_id`, `tbl_leave`.`type_id`, `tbl_leave`.`start_date`, `tbl_leave`.`end_date`,
`tbl_leave`.`total_days`, `tbl_leave`.`reason`, `tbl_leave_type`.`type`, `tbl_employment`.`com_id` as `comid`, `tbl_staff`.`name`
FROM `tbl_leave` JOIN
`tbl_leave_type`
ON `tbl_leave_type`.`id` = `tbl_leave`.`type_id` JOIN
`tbl_employment`
ON `tbl_employment`.`staff_id` = `tbl_leave`.`staff_id` JOIN
`tbl_staff`
ON `tbl_staff`.`id` = `tbl_leave`.`staff_id`
You can look as picture: https://imgur.com/gallery/1Ewku
And this is relationship table: https://imgur.com/gallery/ziKq3
The result I want like this : https://imgur.com/gallery/6NJpR
Thank for your valuable times for this question.
Please try
SELECT distinct `tbl_leave`.`id`, `tbl_leave`.`staff_id`,
`tbl_leave`.`type_id`, `tbl_leave`.`start_date`, `tbl_leave`.`end_date`,
`tbl_leave`.`total_days`, `tbl_leave`.`reason`, `tbl_leave_type`.`type`,
`tbl_employment`.`com_id` as `comid`, `tbl_staff`.`name`
FROM `tbl_leave` JOIN
`tbl_leave_type`
ON `tbl_leave_type`.`id` = `tbl_leave`.`type_id` JOIN
`tbl_employment`
ON `tbl_employment`.`staff_id` = `tbl_leave`.`staff_id` JOIN
`tbl_staff`
ON `tbl_staff`.`id` = `tbl_leave`.`staff_id`;
Please try this solution and let me know if is there any problem occur:
SELECT [Columns] From tbl_staff as staff
JOIN tbl_employment as emp on staff.id = = emp.staff_id
JOIN tbl_leave as leave on staff.id = = leave.staff_id
JOIN tbl_leave_type as ltype on leave.type_id = = ltype.id

MySQL Creat View with all data where date is max

I want to create a view which combines the data with the maximal date from the tables shown in the picture. These should be grouped by the profileID.
Database ERM
The profileIDs are linked to profile.userID.
I tried different approches in my code. The fort one slects the data where date is max, but the join doesn't work. Every profileID will be joined with the same data.
CREATE
ALGORITHM = UNDEFINED
DEFINER = `b91788dd8d05b5`#`%`
SQL SECURITY DEFINER
VIEW fitchallengersql1.profileview AS
Select p.userID,
(SELECT
`bf`.`bodyFat`
FROM
(`fitchallengersql1`.`bodyfatprofile` `bf`
JOIN `fitchallengersql1`.`profile` `p`)
WHERE
((`bf`.`profileID` = `p`.`userID`)
AND (`bf`.`date` = (SELECT
MAX(`fitchallengersql1`.`bodyfatprofile`.`date`)
FROM
`fitchallengersql1`.`bodyfatprofile`)))) AS `bodyFat`,
(SELECT
`bw`.`bodyweight`
FROM
(`fitchallengersql1`.`bodyweightprofile` `bw`
JOIN `fitchallengersql1`.`profile` `p`)
WHERE
((`bw`.`profileID` = `p`.`userID`)
AND (`bw`.`date` = (SELECT
MAX(`fitchallengersql1`.`bodyweightprofile`.`date`)
FROM
`fitchallengersql1`.`bodyweightprofile`)))) AS `bodyWeight`,
(SELECT
`bmi`.`bmi`
FROM
(`fitchallengersql1`.`bmiprofile` `bmi`
JOIN `fitchallengersql1`.`profile` `p`)
WHERE
((`bmi`.`profileID` = `p`.`userID`)
AND (`bmi`.`date` = (SELECT
MAX(`fitchallengersql1`.`bmiprofile`.`date`)
FROM
`fitchallengersql1`.`bmiprofile`)))) AS `bmi`
From profile
In the second one the join works how it should, but I can't figure out a way to select just the data where date is max.
CREATE
ALGORITHM = UNDEFINED
DEFINER = `b91788dd8d05b5`#`%`
SQL SECURITY DEFINER
VIEW `fitchallengersql1`.`profileview` AS
SELECT
`p`.`userID` AS `userID`,
`p`.`privacy` AS `privacy`,
`bs`.`size` AS `bodysize`,
`bw`.`bodyweight` AS `bodyweight`,
`bf`.`bodyFat` AS `bodyfat`,
`bmi`.`bmi` AS `bmi`
FROM
((((`fitchallengersql1`.`profile` `p`
JOIN `fitchallengersql1`.`bodysizeprofile` `bs`)
JOIN `fitchallengersql1`.`bodyweightprofile` `bw`)
JOIN `fitchallengersql1`.`bmiprofile` `bmi`)
JOIN `fitchallengersql1`.`bodyfatprofile` `bf`)
WHERE
((`p`.`userID` = `bs`.`profileID`)
AND (`p`.`userID` = `bw`.`profileID`)
AND (`p`.`userID` = `bmi`.`profileID`)
AND (`p`.`userID` = `bf`.`profileID`))
Hope someone could help me.
Thank you!
fleewe
Hope following query gives what you need. Please follow the pattern and join the rest of the tables. Please note that when the table grows these will definitely have performance issues as this require huge processing.
-- Select the columns that you need
select p.*, lbp.*
from profile p
inner join (
-- get the latest bmiprofile per user profile
select bp1.*
from bmiprofile bp1
inner join (select profileID, max(date) as date from bmiprofile group by profileID) as bp2 on bp1.prfileId = bp2.profileId and bp1.date = bp2.date
) as lbp on lbp.ProfileId = p.userId
-- Join the other tables in similar way
this is only a comment, but I needed formating capability:
Don't place the joining predicates into the where clause if using ANSI join syntax, instead use ON followed by the relevant predicates. e.g.
FROM `fitchallengersql1`.`profile` `p`
JOIN `fitchallengersql1`.`bodysizeprofile` `bs` ON `p`.`userID` = `bs`.`profileID`
JOIN `fitchallengersql1`.`bodyweightprofile` `bw` ON `p`.`userID` = `bw`.`profileID`
JOIN `fitchallengersql1`.`bmiprofile` `bmi` ON `p`.`userID` = `bmi`.`profileID`
JOIN `fitchallengersql1`.`bodyfatprofile` `bf` ON `p`.`userID` = `bf`.`profileID`

Two related queries needs to be one

I know this is a basic thing but SQL is a serious weak point of mine...
I have the following query ("query1")
select
SC.statues, SC_some_real_code
from
[corpdb_gs].[dbo].[Simple_Codes] SC
inner join
[corpdb_gs].[dbo].[real_simple_essentials] RSE
on
SC.statues = RSE.se_statutes
AND
SC.some_real_code = RSE.se_statutes_reason
I need to return only the rows in table [db2].[dbo].[statusYo] where
statusYo.code = "query1".SC.statues
AND
statusYo.reason = "query1".SC.some_real_code
Help?
select * from [db2].[dbo].[statusYo] query2
inner join
(select
SC.statues as statues , SC.some_real_code as some_real_code
from
[corpdb_gs].[dbo].[Simple_Codes] SC
inner join
[corpdb_gs].[dbo].[real_simple_essentials] RSE
on
SC.statues = RSE.se_statutes
AND
SC.some_real_code = RSE.se_statutes_reason) query1
on query1.statues =query2.code
and query1.some_real_code=query2.reason
this will work for you......

MySQL statement, JOIN

I have these tables :
I don't know how I can write a statement, that takes emails from Table "Firm", that have Location_id = '1' and Category_id = '130';
I know that I should use JOINs, but I'm not sure how to go from there.
SELECT Firm.email
FROM Firm
INNER JOIN FirmID ON Firm.firma_id = FirmID.firma_id
WHERE FirmID.location_id = '1'
AND FirmID.Category_id = '130'
Should be as simple as doing the following:
SELECT email
FROM Firm, FirmID
WHERE Firm.firma_id = FirmID.firma_id
AND FirmID.location_id = 1
AND FirmID.category_id = 130;
It does a join behind the scenes, but can be a bit clearer to understand than using the JOIN keyword.
You could do:
SELECT f.email
FROM Firm f
WHERE f.firma_id =
(
SELECT ff.firma_id
FROM FirmID ff
WHERE ff.location_id = 1
AND ff.category_id = 130
)
Using an inner select.
But using JOINS is in the long term the way to go, what have you tried and what's not working?

Rails - How to force associations to use alias table name

p = Patient.find(30)
p.patient_problems
The above code generates the following query
SELECT `patient_problem`.* FROM `patient_problem` WHERE `patient_problem`.`patient_id` = 30 AND (`patient_problem`.`record_status_id` = 1)
But is there any way to assign/use alias table_name like
p.patient_problems(:alias=>'p1') # just for Ex.. This code will not work
p.patient_problems(:alias=>'p2') # just for Ex.. This code will not work
So it will generate the following queries
SELECT `p1`.* FROM `patient_problem` AS `p1` WHERE `p1`.`patient_id` = 30 AND (`p1`.`record_status_id` = 1)
SELECT `p2`.* FROM `patient_problem` AS `p2` WHERE `p2`.`patient_id` = 30 AND (`p2`.`record_status_id` = 1)
Additional Info
My problem is when I try to use joins
p.patient_problems(:all,:joins=>joins)
I get this error
ActionView::Template::Error (Mysql2::Error: Not unique table/alias: 'patient_problem': SELECT `patient_problem`.* FROM `patient_problem` LEFT OUTER JOIN party on party.id = patient_problem.patient_id
LEFT OUTER JOIN party_identifier on party.id = party_identifier.party_id
LEFT OUTER JOIN blood_type on blood_type.id = party.blood_type_id
LEFT OUTER JOIN education_level on education_level.id = party.education_level_id
LEFT OUTER JOIN religion on religion.id = party.religion_id
LEFT OUTER JOIN living_arrangement on living_arrangement.id = party.living_arrangement_id
LEFT OUTER JOIN patient_problem patient_problem on patient_problem.patient_id = party.id and patient_problem.record_status_id = 1
left join (select user_type,username,user_id,auditable_id from (select MAX(id) id from audits where audits.auditable_type = 'PatientProblem' and user_type is not null group by auditable_id ) t inner join audits v on v.id=t.id ) entered_by1 on entered_by1.auditable_id = patient_problem.id
left outer join user user1 on entered_by1.user_id = user1.id
left outer join party as party_user1 on party_user1.id = user1.person_id
LEFT OUTER JOIN patient_patient_search patient_patient_search1 on patient_patient_search1.patient_id = party.id
left join search search1 on patient_patient_search1.patient_search_id = search1.id
and patient_patient_search1.patient_search_id = '75' WHERE `patient_problem`.`patient_id` = 45 AND (`patient_problem`.`record_status_id` = 1) AND ( (patient_problem.occurrence_date > '2013-01-01 00:00:00' and patient_problem.occurrence_date < '2013-06-30 23:59:59' and patient_problem.patient_problem_status_id in (5) and patient_problem.code is not null and patient_problem.code in ('10725009') ) and ( patient_patient_search1.patient_search_id in (75.0) ) ))
Ofcourse I could do some string manipulation on the generated joins query and set alias to patient_problem. But I thought setting alias for associations would be more cleaner since the joins query generated are unpredictable(in my scenario)
I am not sure what the variable joins is or how it was constructed. To alias tables in a join build your query like
Rails 3
PatientProblem.joins("as p1 OUTER JOIN patient_problem as p2 on ...")
or
PatientProblem.find(:all, :joins => "as p1 OUTER JOIN patient_problem as p2 ON ...")
you can make singleton methods for that and write the query one time and use may time like
def self.p1
#your active record query here.
end
and call like
PatientProblem.p1
Update
You can simply change the table name in your code:
Patient.table_name="p2"
I'm not sure if this would break anything else though ... so good luck!
Orignal Answer
One solution may be to define a separate model for each type of patient_problem and then do something like this:
class PatientProblem2 < ActiveRecord::Base
self.set_table_name "p2"
...
end
Another solution may be to use the ActiveRecord query interface which will allows for significant query flexibility:
http://guides.rubyonrails.org/active_record_querying.html
Perhaps you can be more specific on the nature problem you are trying to solve.