Using where in inner join of 3 tables in mysql - mysql

I want to get list of trains available on a particular date between a pair of stations:
These are my tables.
`route`
(
`train_id`,
`Stop_number`,
`Station_id`,
`Arrival_time`,
`Departure_time`,
`Source_distance`
)
`train`
(
`Train_id`,
`Train_name`,
`Train_type`,
`Source_station`,
`Destination_Station`,
`Source_id`,
`Destination_id`
)
`train_status`
(
`Train_id`,
`Available_date`,
`Booked_seat`,
`Waiting_seat`,
`Available_seat`
)
I am creating a mysql database for railway reservation system.
I am new to mysql but still tried to write this query using inner joins .
Please help me work this query.
Select Route.Train_id, Train.Train_name, Train_status.Available_date
FROM Route INNER JOIN Train
ON Route.Train_id = Train.Train_id
INNER JOIN
Train_status ON Train.Train_id= Train_status.Train_id
WHERE (Route.Station_id IN
(Select Source.Station_id
FROM Route AS Source INNER JOIN
Route AS Destination ON Source.Train_id=
Destination.Train_id WHERE (Source.Stop_number-Destination.Stop_number<0)AND
(Source.Station_id=#Source) AND (Destination.Station_id=#Dest) )) AND
(Train_status.Available_Date = #Available_Date)

this is similar try it and let me know if this works or not:
Select Route.train_id, Train.Train_name, Train_status.Available_date
FROM Train
INNER JOIN Train_status ON Train.Train_id= Train_status.Train_id AND Train_status.Available_Date = #Available_Date
INNER JOIN Route AS Source ON Source.Train_id=Train.Train_id and Source.Station_id=#Source
INNER JOIN Route AS Destination ON Destination.Train_id=Train.Train_id and Destination.Station_id=#Dest

Related

SQL Query Count With JOIN

I've the following SQL Query which runs perfectly fine but now i want to calculate the count based on the following scenario:
SELECT d.vseverity, v.vulnstatus, v.vtitleid, d.vtitle
FROM vulnsummary v
JOIN project p ON v.projid = p.projid
AND v.stagename = p.currentstage
JOIN datasets d ON v.vtitleid = d.datasetid
The current Output is:
Now i want to show the count like this way:
High (Open) - 2
High (Closed) - 0
Medium (Open) - 1
Medium (Closed) - 0
Low (Open) - 3
Low (Closed) - 1
Please help me to solve this query, Thank You
You need to CROSS JOIN the distinct sets of severity and status values and then LEFT JOIN that to your table to allow you to count the values of each severity/status combination. Without sample data it's hard to be certain but something like this should work:
SELECT sv.vseverity, st.vulnstatus, COUNT(v.vseverity) AS count
FROM (
SELECT DISTINCT vseverity
FROM datasets
) sv
CROSS JOIN (
SELECT DISTINCT vulnstatus
FROM vulnsummary
) st
LEFT JOIN (
SELECT d.vseverity, v.vulnstatus
FROM vulnsummary v
JOIN project p ON v.projid = p.projid
AND v.stagename = p.currentstage
JOIN datasets d ON v.vtitleid = d.datasetid
) v ON v.vseverity = sv.vseverity AND v.vulnstatus = st.vulnstatus
GROUP BY sv.vseverity, st.vulnstatus
I don't have your full dataset, however, a RIGHT OUTER JOIN to a master volnstatus table will enable (the volnstatus table showing all options i.e. 'Open', 'Closed'). A rough draft example, with only the volnstatus table populated:
SELECT COUNT(s.vulnstatus) CountOf, t.vtype
FROM dbo.vusummary s
RIGHT OUTER JOIN
vusummarytype t
ON s.vulnstatus = t.vtype
GROUP BY t.vtype

Issue With Join Doubling Results

I have seen several posts about this on Stack Overflow, but none of them seems to give me an answer that I can understand.
I am trying to join several relations together in order to get all of the relevant information to output all routes that start in China and end in the United States.
In the SeaRoute relation, the start_port and end_port are stored as INT and in the Port relation the pid corresponds to the start_port and end_port and includes a pcountry column.
I am starting off with just trying to output everything that has a start_port that is in China. I am expecting 3 results from my Record relation as those are the only ones that start with China in the table; However, I am receiving 6 records at the output (all of the results appear to have been doubled if I go back and audit what's in the table).
While I want the right answer, I am more concerned that I have a fundamental misunderstanding of Inner Join and the other Join methods. What am I doing wrong?
SELECT *
FROM Record
INNER JOIN Goods AS Go_data
ON Record.gid = Go_data.gid
LEFT JOIN SeaRoute AS SR
ON Record.rid = SR.rid
RIGHT JOIN (SELECT pid, pcountry AS starting_port_country
FROM Port
INNER JOIN SeaRoute AS SR ON Port.pid = SR.start_port
WHERE Port.pcountry = 'China')
AS start_port_table ON SR.start_port = start_port_table.pid
From the looks of your query, you want to be INNER JOINing between the records that you have only on the routes that you want.
You know all of the SeaRoutes that start in China and end in the United States already, you do however need to join to the Ports table twice like so:
SELECT sr.rid,
sp.pcountry AS starting_port_country,
ep.pcountry AS end_port_country
FROM dbo.SeaRoute sr
INNER JOIN dbo.Port sp ON sp.pid = sr.start_port
INNER JOIN dbo.Port ep ON ep.pid = sr.end_port
WHERE sp.pcountry = 'China'
AND ep.pcountry = 'United States'
Then you just need to join that to your main query:
SELECT *
FROM Record
INNER JOIN dbo.Goods AS Go_data ON Record.gid = Go_data.gid
INNER JOIN
(
SELECT sr.rid,
sp.pcountry AS starting_port_country,
ep.pcountry AS end_port_country
FROM dbo.SeaRoute sr
INNER JOIN dbo.Port sp ON sp.pid = sr.start_port
INNER JOIN dbo.Port ep ON ep.pid = sr.end_port
WHERE sp.pcountry = 'China'
AND ep.pcountry = 'United States'
) ports ON ports.rid = Record.rid
There's no way I can explain joins to you any clearer than this page can:
https://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins

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`

Use inner join, left join or right join for join 2 tables

I'm realizing a project which raises me the next tables:
For being more specific: First table:
'docs' => doc_id, doc_type_type_id, clients_cli_id
where doc_type_type_id
invoices
reference guides
Second Table:
'client' => cli_id
What I try to do is to join Client with doc that My query is:
Show Client with his invoice and reference guide:
SELECT c.cli_name, d1.doc_file as f1 , d2.doc_file as f2 FROM clients c INNER JOIN docs d1 ON d1.client_cli_id = c.cli_id INNER JOIN docs d2 ON d2.client_cli_id = c.cli_id WHERE d1.doc_fec=d2.doc_fec
select * from docs
inner join client on docs.clients_cli_id = client.cli_id
where doc_type_type_id = 1
Something in this format should give you all invoices joined to client.

How to search where some data is in table 1 and other data is in table 3 with both having a UUID the same

I have 3 tables
For instance
Salestable
-ID
-variableB
-customerUUID
-variableC
Customertable
-customerUUID
-contractUUID
Contracttable
-contractUUID
-variableD
So I am currently doing a SQL Query on salestable
Like:
SELECT DISTINCT variableB FROM Salestable WHERE variableD = "blah";
How can I do this? Where I can find the contract associated with the current salestable?
A bit more info
They are all a 1:1 relationship - so Contracttable is tied to 1 Customertable which is tied to 1 salestable
There is a LOT of data in my database thousands of entries - this query does not run constantly but does need to run somewhat efficent.
SELECT a.*
FROM SalesTable a
INNER JOIN CustomerTable b
ON a.customerUUID = b.customerUUID
INNER JOIN Contracttable c
ON b.contractUUID = c.contractUUID
WHERE c.variableD = 'valueHere'
To further gain more knowledge about joins, kindly visit the link below:
Visual Representation of SQL Joins
If you sure the contract exists use this (othewise swap INNER FOR LEFT):
SELECT variableB, variableD
FROM Salestable t1
INNER JOIN Customertable t2 ON (t1.customerUUID = t2.customerUUID)
INNER JOIN Contracttable t3 ON (t3.contractUUID = t2.contractUUID)
WHERE variableD = "blah"
GROUP BY t1.variableB