I have a table in my DB called ORDERS and it looks like this:
ID_section (int), ID_price (int), ID_city (int), ID_company (int)
And I want to use the JOIN method to set names to the ID's.
What I would do is:
SELECT * FROM ORDERS
JOIN sections ON sections.id=orders.ID_section
JOIN prices ON prices.id=orders.ID_price
JOIN cities on cities.id=orders.ID_cities
JOIN companies ON companies.id=orders.ID_company
But the point is, that in ORDERS table can be inserted value of 0 and it means - all the sections/prices/cities/companies, but when I run my query, only the values, that their ID exist in the other table show up.
Any ideas? Thanks.
If I understand you question correctly and having, for example, ID_section = 0 means that the order belongs to all the section then the following query should do the trick.
SELECT * FROM ORDERS
JOIN sections ON sections.id=orders.ID_section OR orders.ID_section = 0
JOIN prices ON prices.id=orders.ID_price OR orders.ID_price = 0
JOIN cities on cities.id=orders.ID_cities OR orders.ID_cities = 0
JOIN companies ON companies.id=orders.ID_company OR orders.ID_company = 0
If, on the other hand, you want to retrieve all orders regardless if they have sections, prices, etc. associated, then it is sufficient to put LEFT JOIN where you have JOIN. (But this situation does not result from your question! I only added it because people seem to understand that.)
Use LEFT JOIN instead of JOIN (which is a shorthand for INNER JOIN)
Experiment with LEFT and RIGHT OUTER JOIN s and you'll be able to figure out what you need to do. Basically a LEFT or RIGHT OUTER JOIN will insert NULLS into columns where no data exists but still do the joins.
There are various resources on the web that explain this.
Related
I am newish to SQL and Join statements and I am way out of my league at the moment
I currently have 6 Database Tables that are all linked to the main 7th table based on the main tables ID, however all the information in the other 6 tables are looped and so have several displayed results to the one main tables ID.
Is it possible to join them all into one Join Statement so I can have a results so that everyones information from the main table also shows their information from the 6 other linked tables
So basically when they all have the informationed joined I want to be able to Display all information on a webpage
so I was wondering do I need to do multiple JOIN statements or just one Longer one?
I have Included some Images below that explain it visually. See examples 1 and 2
The columns that are highlighted in yellow are looped to have many results:
2. This is the example of how the information is looped into the
database where there are many Race_id sharing to the same inf_id:
Im not so sure how it will look once it has been joined since some of the information is looped into many Id's and not sure if that means it need to duplicate the column or the rows?? any help would be greatly appreciated.
You could use left join eg for the first tables influencer, social, activities
select i.*, s.follower, s.Social_Medial_URL, a.activity, a.result
from influencer i
left join social s on s.inf_id = i.id
left join activities a on a.inf_id = i.id
you can procede yourself adding the left join for the others tables using the same rules
select i.*
, s.follower_count
, s.social_media_url
, a.compete_activity
, a.compete_results
from influencers i
left join inf_other_social s on s.inf_id = i.id
left join inf_compete_activity a on a.inf_id = i.id
LIMIT 0, 25
I think you are confused about primary key and foreign key. the picture you have given is clearly elaborate everything. as per your db diagram the query might be like this...
select * from
Influencer i
Left Join Social s on i.inf_id = s.inf_id
Left Join Owned_Equip o on i.inf_id=o.inf_id
Left Join Ages_Interacted a on i.inf_id = a.inf_id
Left Join Activities ac on i.inf_id = ac.inf_id
Left Join Awards aw on i.inf_id = aw.inf_id
Left Join History h on i.inf_id = h.inf_id
By using this above query you can get all the information of Influencer and related to him (Social,Owned_Equip,Activities,Award etc) whether they exists or not. If you using only "Join" not "Left Join" then you can only find those records which is common for a single influencer to it's related entities/tables which might you say. as an example: say Influencer (id = 1 , suppose name is dan) after inner join we can get only records related to dan ( his social,owned equipments,activites,awards and so on if those tables contains record related to dan record)
Im having a bit of difficulty with getting user information from one place to another.
There are 3 tables dbo.gr_usersource and dbo.gr_task and dbo.gr_user
In the dbo.gr_task table a column is filled with values that match entries in dbo.gr_usersource table that has another value that corresponds to the value in the dbo.gr_user table. You could call it a reference table between dbo.gr_task and dbo.gr_user tables.
My query looks like this;
select
dbo.gr_task.task_number
, dbo.gr_task.task_name
, dbo.gr_task.task_description
from dbo.gr_task
left join dbo.gr_user AS Handler
on dbo.gr_usersource.usersource_user = Handler.user_id
and dbo.gr_task.task_handler = dbo.gr.usersource.usersource.id
The last step would be to get the column user_name from table user when the join is working.
You have missed mediator table in your join so use as per below-
SELECT dbo.gr_task.task_number,dbo.gr_task.task_name, dbo.gr_task.task_description
FROM dbo.gr_task AS gt
LEFT JOIN dbo.gr_usersource gus ON gt.task_handler=gus.usersource.id
LEFT JOIN dbo.gr_user AS gu ON gus.usersource_user=gu.user_id;
Note: If you want only matching rows in all 3 tables then you should use normal join instead of left join.
This may work for you.
Note that there are no columns from your joined tables in your select list so left joins would have no impact on your result set.
Inner joins will filter your results set even if you bring back no columns, i.e., enforce the join condition to match rows in both tables.
SELECT
t.task_number
, t.task_name
, t.task_description
FROM dbo.gr_task t
INNER JOIN dbo.gr_usersource us
ON us.usersource.id = t.task_handler
INNER JOIN dbo.gr_user u
ON u.user_id = us.usersource_user
Below is my sql statement
SELECT a.purchase_id,
b.username,
a.purchase_packageid,
a.purchase_tradelimit,
a.purchase_pincode,
a.purchase_datetime,
c.packages_name ,
FROM purchase a,
accounts b,
packages c
WHERE a.purchase_userid=b.UserId
AND c.packages_id=a.purchase_packageid
Basically the issue is I got 3 tables
Accounts
Purchase
Packages
The main table is Purchase, inside the table there is purchase_userid , which I need to use it to get username from table accounts
So the problem now is I got rows where the purchase_userid is blank, because its blank, it won't draw its record as null.
The only record that show in this sql statement is only those with purchase_userid,
As the value for purchase_userid will be fill up later for my web app,
I still want to select rows without purchase_userid and those with purchase_userid
Thanks for helping !!
You need to use a left join to load all records in Purchase even when no matching records are found in Accounts.
SELECT a.purchase_id, b.username, a.purchase_packageid, a.purchase_tradelimit, a.purchase_pincode, a.purchase_datetime, c.packages_name
FROM purchase a LEFT JOIN accounts b
ON a.purchase_userid=b.UserId
JOIN packages c
ON c.packages_id=a.purchase_packageid
This post explains the different kinds of joins pretty well: What's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN?
You're using the old-timey syntax for INNER JOINs between your tables, when what you need is LEFT JOIN operations. Try this:
SELECT a.purchase_id,
b.username,
a.purchase_packageid,
a.purchase_tradelimit,
a.purchase_pincode,
a.purchase_datetime,
c.packages_name
FROM purchase AS a
LEFT JOIN accounts AS b ON a.purchase_userid = b.UserId
LEFT JOIN packages AS c ON a.purchase_packageid = c.packages_id
This works better for you because the kind of JOIN you were using suppresses records from your a table when they weren't matched in your b or c table. This LEFT JOIN will leave the a table records in place, and put NULL values where you are calling for data from the other two.
So, alright, I have a few tables. My current query runs against a "historical" table. I want to do a join of some kind to get the most recent status from my Current table. These tables share a like column, called "ID"
Here's the structure
ddCurrent
-ID
-Location
-Status
-Time
ddHistorical
-CID (AI field to keep multiple records per site)
-ID
-Location
-Status
-Time
My goal now is to do a simple join to get all the variables from ddHistorical and the current Status from ddCurrent.
I know that they can be joined on ID since both of them have the same items in their ID tables, I just can't figure out which kind of join is appropriate or why?
I'm sure someone may provide a specific link that goes into great detail explaining, but I'll try to summarize it this way. When writing a query, I try to list the tables from the position of what table do I want to get data from and have that as my first table in the "FROM" clause. Then, do "JOIN" criteria to other tables based on relationships (such as IDs). In your example
FROM
ddHistorical ddH
INNER JOIN ddCurrent ddC
on ddH.ID = ddC.ID
In this case, INNER JOIN (same as JOIN) the ddHistorical table is the left table(listed first for my styling consistency and indentation) and ddCurrent is the right table. Notice my ON criteria that joins them together is also left alias.column = right alias table.column -- again, this is just for mental correlation purposes.
an Inner Join (or JOIN) means a record MUST have a match on each side, otherwise it is discarded.
A LEFT JOIN means give me all records in the LEFT table (ddHistorical in this case), regardless of a matching in the right-side table (ddCurrent). Not practical in this example.
A RIGHT JOIN is the reverse... give me all records from the RIGHT-side table REGARDLESS of a matching record in the left side table. Most of the time you will see LEFT-JOINs more frequently than RIGHT-JOINs.
Now, a sample to mentally get the left-join. You work at a car dealership and have a master table of 10 cars that are sold. For a given month, you want to know what IS NOT selling. So, start with the master table of all cars and look at the sales table for what DID sell. If there is NO such sales activity the right-side table will have NULL value
select
M.CarID,
M.CarModel
from
MasterCarsList M
LEFT JOIN CarSales CS
on M.CarID = CS.CarID
AND month( CS.DateSold ) = 4
where
CS.CarID IS NULL
So, my LEFT join is based on a matching car ID -- AND -- the month of sales activity is 4 (April) as I may not care about sales for Jan-Mar -- but would also qualify year too, but this is a simple sample.
If there is no record in the Car Sales table it will have a NULL value for all columns. I just happen to care about the car ID column since that was the join basis. That is why I am including that in the WHERE clause. For all other types of cars that DO have a sale it will have a value.
This is a common approach you will see in querying where someone looking for all regardless of other... Some use a where NOT EXIST ( subselect ), but those perform slower because they test on every record. Having joins is much faster.
Other examples may be you want a list of all employees of a company, and if they had some certification / training to show it... You still want all employees, but LEFT-JOINING to some certification/training table would expose those extra field as needed.
select
Emp.FullName,
Cert.DateCertified
FROM
Employees Emp
Left Join Certifications Cert
on Emp.EmpID = Cert.EmpID
Hopefully these samples help you understand better the relationship for queries, and now to actually provide answer for your needs.
If what you want is a list of all "Current" items and want to look at their historical past, I would use current FIRST. This might be if your current table of things is 50, but historically your table had 420 items. You don't care about the other 360 items, just those that are current and the history of those.
select
ddC.WhateverColumns,
ddH.WhateverHistoricalColumns
from
ddCurrent ddC
JOIN ddHistorical ddH
on ddC.ID = ddH.ID
If there is always a current field then a simple INNER JOIN will do it
SELECT a.CID, a.ID, a.Location, a.Status, a.Time, b.Status
FROM ddHistorical a
INNER JOIN ddCurrent b
ON a.ID = b.ID
An INNER JOIN will omit any ddHistorical rows that don't have a corresponding ID in ddCurrent.
A LEFT JOIN will include all ddHistorical rows, even if they don't have a corresponding ID in ddCurrent, but the ddCurrent values will be null (because they're unknown).
Also note that a LEFT JOIN is just a specific type of outer join. Don't bother with the others yet - 90% or more of what you'll ever do will be INNER or LEFT.
To include only those ddHistorical rows where the ID is in ddCurrent:
SELECT h.CID, h.ID, h.Location, h.Status, c.Status, h.Time
FROM ddHistorical h
INNER JOIN ddCurrent c ON h.ID = c.ID
If you want to include ddHistorical rows even if the ID isn't in ddCurrent:
SELECT h.CID, h.ID, h.Location, h.Status, c.Status, h.Time
FROM ddHistorical h
LEFT JOIN ddCurrent c ON h.ID = c.ID
If all ddHistorical rows happen to match an ID in ddCurrent, note that both queries will return the same result.
I have to get data from two SQL tables but I am unsure of what join to use and the same tables have the same customers_id table would I use an inner join?
table - customers
customers_id
customers_firstname
customers_lastname
customers_email_address
table - orders
customers_id
customers_street_address
customers_suburb
customers_city
customers_postcode
customers_state
customers_country
It depends on what results you want. If you want every record in Customers regardless of whether there is a matching record in orders the you would use an LEFT OUTER JOIN. If not you would use an INNER JOIN. This is the article I typically refer people to for a basic explanation of joins.
An INNER JOIN would look like this:
SELECT c.customers_id,
c.customers_firstname,
c.customers_lastname,
o.customers_street_address,
o.customers_city,
o.customers_postcode,
o.customers_state
FROM customers as c
INNER JOIN orders as o
ON c.customers_id = o.customers_id
I purposely did not do select *. Try to get into the habit of only selecting the columns you want from tables instead of everything.
The join you should use depends on which information you are trying to retain, based on the customer ID. If you're looking to retain all of the information from customers even if there is no match with orders you would use a left join. Conversely, if you wanted to retain all the information from orders even if there were no match with customers you would use a right join.
If you want to return all of the information, and combine rows which have a match, use a full join. Finally, you can use an inner join if you only want the rows which have a match from either table.
the same tables have the same customers_id table
I think you meant to say they have a common column, being customers_id, in which case you can use NATURAL JOIN.
INNER JOIN Ya you can use it.
You can write below query to get your all data from two tables.I am going to write full join query for you.y
select customers.customers_firstname,
customers.customer_lastname,
orders.customers_city
from customers
INNER JOIN orders
ON customer.customers_id = orders.customers_id