After yeas of lurking on stackoverflow, always finding my answer), I finally need to post my own question.
I new to MySQL and have been using access query designer to help me learn/convert my query to SQL.
This has work fine until I tried to convert a access query that uses another query (sub-query).
Here is the finished Access query that works:
SELECT all_assm_start_stop.*, employee.first_name
FROM all_assm_start_stop LEFT JOIN employee ON all_assm_start_stop.employee_id = employee.employee_id
all_assm_start_stop is based on this access query:
(SELECT assemblies.assemblies_id, assemblies.assembly_name, labor.start_time, labor.stop_time, labor.number_completed, labor.employee_id, assemblies.product_id
FROM labor RIGHT JOIN assemblies ON labor.assemblies_id = assemblies.assemblies_id
WHERE (((assemblies.product_id)=2)))
I've been researching most the day about MySQL sub-queries but can't figure out how to convert this.
Any help is very much appreciated!
As someone who has had to do this too many times, this is the most direct/literal conversion method I have found:
SELECT all_assm_start_stop.*, employee.first_name
FROM ([original query]) AS all_assm_start_stop
LEFT JOIN employee ON all_assm_start_stop.employee_id = employee.employee_id
;
(Note the [original_query] is where you would put the second one you supplied, I posted the answer in this way for brevity and clarity/generality.)
Edit: If that query was used in a lot of other queries, you might want to consider making it a VIEW instead.
SELECT a.assemblies_id
, a.assembly_name
, l.start_time
, l.stop_time
, l.number_completed
, l.employee_id
, a.product_id
, e.first_name
FROM assemblies a
LEFT
JOIN labor l
ON l.assemblies_id = a.assemblies_id
LEFT
JOIN employee e
ON e.employee_id = a.employee_id
WHERE a.product_id = 2
Related
I am having some strange issue with the SQL statement below. The result groups by user IDs and some of them turn out right but for one of them (user ID = 1) the "initial_average" is multiplied by 3. I really have no idea why.. Is there something wrong with the structure of the statement? If it is not clear, the aim is to sum the field "initial_avg" in the "tasks" table and have it broken out by user. Some help with this is much appreciated. I am using MySQL.
SELECT sum(initial_avg) AS initial_average
, sum(initial_std) AS initial_standard_dev
, tasks.user
, hourly_rate
FROM tasks
INNER JOIN user_project
ON tasks.user=user_project.user
AND tasks.project=59
AND tasks.user=1
GROUP BY tasks.user
I just solved it by adding another "and" clause (AND user_project.project=59 )
Optimize your query (Try it):
SELECT SUM(initial_avg) AS initial_average, SUM(initial_std) AS initial_standard_dev, tasks.user, hourly_rate FROM tasks INNER JOIN user_project ON tasks.user = user_project.user AND tasks.project = User_project.project WHERE tasks.project = 59 AND tasks.user = 1 GROUP BY tasks.user, hourly_rate
I have a problem which I cant figure out, and have looked on google and similar questions on here, but they are just not quite the same.
I am trying to build a MySQL Query which has two parts, the first is easy and i have done this fine, as it uses existing relationships, see...
SELECT
clientsites.SiteName,
clients.ClientName,
pafaddresses.PostTown,
pafaddresses.PostCode,
CONCAT("XXXXXXX", Replace(UPPER(pafaddresses.PostCode),' ','')) AS JouneyKeytemp,
clientsites.SiteType
FROM clientsites
INNER JOIN clients ON clientsites.ClientFk = clients.ClientPk
INNER JOIN pafaddresses ON clients.ActualPAF = pafaddresses.id
You will see from this code that an alias is generated which concats two postcodes and looks like xxxxxxxyyyyyy, this does work but for obvious reasons ive removed the actual postcodes.
What I now what to do is to bring in two fields from an unrelated table called Journeys:
SELECT
JourneyKey,
SingleDistance,
SingleTime
FROM journeys
I want to bring in SingleDistance and SingleTime, where the Journey Key = Generated Alias of JourneyKeyTemp.
I have tried adding the following:
INNER JOIN journeys ON JouneyKeytemp = journeys.JourneyKey
But I just keep getting a syntax error.
Any help would be appreciated.
Repeat the expression in join predicate:
INNER JOIN journeys
ON CONCAT("XXXXXXX", Replace(UPPER(pafaddresses.PostCode),' ','')) = journeys.JourneyKey
Or you can create a subquery:
select * from(
SELECT
clientsites.SiteName,
clients.ClientName,
pafaddresses.PostTown,
pafaddresses.PostCode,
CONCAT("XXXXXXX", Replace(UPPER(pafaddresses.PostCode),' ','')) AS JouneyKeytemp,
clientsites.SiteType
FROM clientsites
INNER JOIN clients ON clientsites.ClientFk = clients.ClientPk
INNER JOIN pafaddresses ON clients.ActualPAF = pafaddresses.id)t
INNER JOIN journeys ON t.JouneyKeytemp = journeys.JourneyKey
I have a rather big SQL statement that I am working with in MS Access 2010. Here it goes:
SELECT
W.ID AS wid,
W.wpt_ty AS ty,
W.wpt_num AS num,
W.wpt_nxt AS nxt,
W.latdeg AS lat,
W.londeg AS lon,
W.alt AS alt,
W.mission_id AS mid,
W.ctg1 AS ctg1,
W.ctg2 AS ctg2,
W.ctg3 AS ctg3,
W.ctg4 AS ctg4,
W.wpt_index AS indx,
W.vel AS vel,
W.tu AS tu,
R.route_num AS rnum,
R.AC_num AS ac,
R.route_type AS rtype,
R.LastUpdatedOn AS d8,
R.LastUpdatedBy AS auth,
R.flight_wpt_count AS wfcount,
M.mission_name AS msnName,
V.Description AS vstatus,
R.disallowed_reason_id AS did,
CW.wpt_num AS c1num,
CR.matching_route_id AS c1mrid,
CW.wpt_index AS c1indx,
CRU.runway_name AS c1rnwy,
CR.route_num AS c1rnum
FROM Validation AS V
(RIGHT JOIN Runways AS CRU
INNER JOIN (Routes CR
INNER JOIN Waypoints CW ON CR.ID = CW.route_id)
ON Runways.ID = Routes.runway_id
INNER JOIN ((Missions as M
INNER JOIN Routes AS R ON M.ID = R.mission_id)
INNER JOIN Waypoints AS W ON (R.ID = W.route_id)
AND (M.ID = W.mission_id)) ON
V.ID = R.validated
WHERE (((R.matching_route_id)=307543) AND ((R.validated) <> 0 ))
AND (((CW.mission_id)=mid) AND ((CW.wpt_num) = (ctg1))))
If you look at the bottom, you can see am I referencing the values ctg1 and mid on a Right Join while the Inner Joins reference other literal values. Eventually I will want to do the same for ctg2, ctg3, and ctg4
Right now I am running these as 2 separate queries but finding it to be way too slow. If I can join combine the queries (sort of like how I am showing here) it could speed things up greatly. But I am at a loss for how to:
Using select values earlier in said query from the Inner/Left join and push them into values needed on the Right join.
I may be using joins incorrectly, but I thought they had to do with combining data from possible the same tables, just on different pivot points.
How to use the MS Access GUI to help write a query like this.
I know this is for MS Access but I am tagging for MySQL just in case there are similar queries there which can be ported to MS Access?
Have you tried using UNION for this?
It would allow you to execute this query (As two queries, which you mentioned as a possibility), and join the results for your output.
Be warned, it will eat up (only show one of) your duplicates in the results set.
I also suggest reading up on the different types of joins for your own benefit, in the following answer:
MYSQL Joins
I am in the process of building a dashboard and need to extract some data from a somewhat complex schema.
I have a select statement (see below) that I am using to extract information, but need to conduct some filtering on part of the select statement, and I'm struggling.
select distinct j.id 'Job_Id'
, js.outcome 'Outcome'
,(select string from property where parent_sheet_id = ps.id and name= 'Build_Type') as 'Build_Type'
from job j, job_step js, property_sheet ps, property p
where j.id = js.job_id
and ps.entity_id=js.id
and ps.id=p.parent_sheet_id
and ps.entity_type='step'
and p.name = 'Id'
group by j.id
order by j.id desc;
I am sure that there is a better way of doing this query, and I would appreciate any other suggestions, but I am mostly attempting to place a filter on the nested select statement which has an alias of "Build_Type", but when I try it appears not to work. I've read some blogs that this is not possible, so I am a little stuck.
Any help would be much appreciated.
Thanks.
select
ps.id,
Build_Type.string
from
property_sheet as ps
left join
property as Build_Type
on ps.id = Build_Type.parent_sheet_id and Build_Type.name = 'Build_Type'
where Build_Type....
I wonder if someone can help me. I want to replicate the following SQL query using LINQ in VB.Net.I'm a little unclear on how to do subqueries / aggregates.
Thanks
SELECT *
FROM Server S
INNER JOIN ServerHDD H
ON S.Server_ID = H.Server_ID
INNER JOIN (SELECT MAX(ServerHDD_ID) AS ServerHDD_ID
FROM ServerHDD
GROUP BY Server_ID, Letter) Filter
ON H.ServerHDD_ID = Filter.ServerHDD_ID
ORDER BY S.Hostname, H.Letter
Got this as below in C# => need VB.Net Conversion please.
from S in SERVER
join H in SERVERHDD on S.Server_ID equals H.Server_ID
join FILTER in
(from s in SERVERHDD group s
by new {s.Server_ID, s.Letter}
into groupedServerHDD select new
{
SERVERHDD_ID = groupedServer.Sum(gS=>gS.ServerHDD_ID)
}
)
on H.ServerHDD_ID equals FILTER.SERVERHDD_ID
orderby S.Hostname, H.Letter
select S
This is my most favorite page regarding this topic. I love LINQ to SQL (and wish they intended to continue support for it over Entity Framework...) http://msdn.microsoft.com/en-us/vbasic/bb688085.aspx. On this page you will find all the answers to your querying needs. It is hard to format the query here without something to test it against!
Your inner joins go away with the simple join syntax of LtS. You can either say .Max() on your inner select or Max(pseudo functoid here) like this:
From p2 In g _
Where p2.UnitPrice = g.Max(Function(p3) p3.UnitPrice) _
Select p2
There are a couple of LINQ learning tools out there that are pretty cool.
This one is my favourite... LinqPad. But you might also want to check out Linqer.
You should be able to paste your code into one of them apps and it will show you how its converted. Hope they come in handy :)