SQL LEFT JOIN in history table - sql

I prepared an sqlFiddle, located here: http://sqlfiddle.com/#!2/951c1/2/1
I have 3 tables (cars, colors, and car_color_history). In colors there are the colors with some kind of metadata I am interested in. In cars, there are a bunch of cars with a 'wanted_color' key which tells the car to change to the given color. In car_color_history, there are all the entries, on what specific time a car had what color.
What I want now is a view/select statement, to get all cars with the current and the wanted color information.
My first idea was to do this with left joins and some kind of GROUP BY magic, but up until now, I could not get that to work
A working solution is the second select in the fiddle with subselects. Am I correct that that is not a pretty solution as it is slow? Plus i do have to provide the subselect for each displayed column :(
Anybody have a solution?

SQL Fiddle
select
ca.carkey,
description,
cow.other_info as wanted_color,
cco.other_info as current_color,
cch.datetime as current_color_datetime
from
cars ca
left join
colors cow on ca.wanted_color = cow.colorkey
left join (
select distinct on (carkey) *
from car_color_history
order by carkey, datetime desc
) cch using(carkey)
left join
colors cco on cch.colorkey = cco.colorkey

Related

Access SQL Lookup - Dropdown Columns

I have looked for a similar issue with no luck. Maybe I don't know the right term to search for.
This seems so simple, but I just can't get it after spending many hours trying different approaches.
I have a dropdown to select contracts which shows some ids for related fields. How can I get those IDs to show the value of another column.
SELECT tbl_contracts.ID, tbl_contracts.contract_name, tbl_contracts.firm_id, tbl_contracts.agency_id
FROM tbl_contracts;
image of dropdown
I would like the IDs shown for agency_id and firm_id to list the company_name from their respective table "tbl_firm_agencies" where the tbl_contracts looks them up from. I've tried INNER JOINS but when I do, I can only line items to show when both agency AND firm exist, so my dropdown get cut off quite a bit.
Simply LEFT JOIN to those lookup tables as opposed to INNER JOIN. Adjust table and field names to actual ones in query below. Also, the parentheses are required in MS Access SQL.
SELECT c.ID, c.contract_name, f.firm_name, a.agency_name
FROM (tbl_contracts c
LEFT JOIN tbl_firms f
ON c.firm_id = f.firm_name)
LEFT JOIN tbl_agencies a
ON c.agency_id = a.agency_name;

SQLite Subqueries and Inner Joins

I was doing a practice question for SQL which asks to create a list of album titles and unit prices for the artist "Audioslave" and find out how many records are returned.
Here is the relational database picture given in the question:
Initially, I used an inner join to retrieve the list and actually got the correct answer (40 records returned). The code is shown below:
select a.Title, t.UnitPrice
from albums a
inner join tracks t on t.AlbumId = a.AlbumId
inner join artists ar on ar.ArtistId = a.ArtistId
where ar.Name = 'Audioslave';
Although I finished the question, I was curious to try to solve this problem using nested subqueries instead and tried to first retrieve the AlbumId and UnitPrice from tracks. I got the correct answer but not the correct list (the question asked for album title and not AlbumId). Here is the code:
select AlbumId, UnitPrice
from tracks
where AlbumId in (
select AlbumId
from albums
where ArtistId in (
select ArtistId
from artists
where Name = 'Audioslave'));
In order to solve the problem with the list, I tried combining the previous codes. However, I get a completely different amount of records being returned (10509).
select a.Title, t.UnitPrice
from albums a
inner join tracks t
where a.AlbumId in (
select AlbumId
from albums
where ArtistId in (
select ArtistId
from artists
where Name = 'Audioslave'));
I don't understand what I'm doing wrong with the last code...Any help would be appreciated! Also, sorry if I wrote too much, I just wanted to convey my thinking process clearly.
Some databases (SQLite, MySQL, Maria, maybe others) allow you to write an INNER JOIN without specifying ON, and they just cross every record on the left with every record on the right in that case. If there were 2 albums and 3 tracks, 6 rows would result. If the albums were A and B, and the tracks were 1, 2 and 3, the rows would be the combination of all: A1, A2, A3, B1, B2, B3
Other databases (Postgres, SQLServer, Oracle, maybe others) refuse to do it unless you specify ON. To get an "every row on the left combined with every row on the right" you have to write CROSS JOIN (or write an inner join with an ON that is always true)
It might help your mental model of what happens during a join to consider that the db takes all the rows on the left and connects them to all the rows on the right, then for each combination of rows, assesses the truth of the ON clause, and the WHERE clause, before deciding to return the row
For example, this will return 10509 rows:
SELECT * FROM albums INNER JOIN tracks ON 1=1
The on clause is always true
This will return 10509 tracks, but only if the query is run on Monday
SELECT * FROM albums INNER JOIN tracks ON strftime('%w', 'now') = 1
What goes in the ON or WHERE doesn't have to have anything to do with the data in the table.. it just has to be something that resolves to a Boolean

SQL Query Results Using Joins

I'm trying to do this query to display the names of the stores and the quantity of each book sold with only using joins but I tried to use
SELECT DISTINCT x.stor_name, t.title, s.qty
FROM stores x
INNER JOIN discounts d
ON x.stor_id=d.stor_id
INNER JOIN salesdetail s
ON d.stor_id=s.stor_id
INNER JOIN titles t
ON s.title_id=t.title_id
ORDER BY s.qty desc;
but that only displayed one of the stores results set for 'Bookbeat'.
I tried to use Left, Right & Full Outer joins to no avail so I'm wondering how I would go about doing that query to display the names for the other stores that are not displaying their result set. As there is 7 stores and only 1 is displaying it's results.
The link is a pastebin to the database.
And this is the schema.
It's hard to say without more information about your schema - it strikes me as wrong-ish that you're joining to discounts only on stor_id. I'd expect discounts to be applied to different titles, not store-wide... and I wouldn't expect discounts to be always-enabled. Try running it without the discounts inner join. Futzing around with "Distinct" and outer joins is almost always the wrong approach with things like this
I see from your profile you're a first-year. Is this schoolwork? How do I ask and answer homework questions?

How should I JOIN my tables?

I'm learning C# and some SQL server, and now i am trying to get information from my small database.
I have two tables: Movie and MovieHandler.
In the table Movie, i have MovieCodeLable, which is a uniqe number, and the Title of the movie.
In the MovieHandler table, i have MovieCodeLable which is the same as in my Movie table, and i have also her the colum InStore, which is eighter 0 or 1 for not in store or in store.
I'm trying to display the Title for the movies which is not in the store. But i find it hard figure out how to join tables.
I have tried this SQL query:
SELECT Title
FROM Movie
JOIN MovieCodeLable
ON MovieHandler.MovieCodeLable
WHERE InStore = 0
Since i only get errors trying this query in Visual Studio 2012, i've probably missed something fundametal with SQL and JOINS, but i hope that someonw could make JOINS smooth as butter for me and others, struggeling to learn it.
Your JOIN is wrong and your ON clause is incomplete. The JOIN should involve the names of the 2 tables that you are joining, which in this case is Movie and MovieHandler The ON should be expression of format A = B. So your query should be:
SELECT Title
FROM Movie
JOIN MovieHandler
ON Movie.MovieCodeLable = MovieHandler.MovieCodeLable
WHERE InStore = 0
You need to specify both JOIN fields
SELECT Title
FROM Movie
JOIN MovieHandler
ON Movie.MovieCodeLable = MovieHandler.MovieCodeLable
WHERE InStore = 0
You have to do the query like this
SELECT Title
FROM Movie
JOIN MovieHandler
ON Movie.MovieCodeLable = MovieHandler.MovieCodeLable
WHERE InStore = 0
You had to complete the ON condition.You need to specify the columns to match after ON condition.Go to this link there is explanations with tables http://www.w3schools.com/sql/sql_join.asp
I do it this way in oracle. Not sure if it will work for you...
Try:
Select Mv.Title
,other_columns
from Movie Mv
,MovieHandler Mvh
Where Mv.MovieCodeLable = Mvh.MovieCodeLable
and (whatever other criteria you want
As long as MovieCodeLable is unique you're ok
Other_columns can be any column of either table format with table.column syntax (I use table shortcuts Mv and Mvh to reference the tables, I don't know if this is legal for non-oracle)

Aggregation with two Joins (MySQL)

I have one table called gallery. For each row in gallery there are several rows in the table picture. One picture belongs to one gallery. Then there is the table vote. There each row is an upvote or a downvote for a certain gallery.
Here is the (simplified) structure:
gallery ( gallery_id )
picture ( picture_id, picture_gallery_ref )
vote ( vote_id, vote_value, vote_gallery_ref )
Now I want one query to give me the following information: All galleries with their own data fields and the number of pictures that are connected to the gallery and the sumarized value of the votes.
Here is my query, but due to the multiple joining the aggregated values are not the right ones. (At least when there is more than one row of either pictures or votes.)
SELECT
*, SUM( vote_value ) as score, COUNT( picture_id ) AS pictures
FROM
gallery
LEFT JOIN
vote
ON gallery_id = vote_gallery_ref
LEFT JOIN
picture
ON gallery_id = picture_gallery_ref
GROUP BY gallery_id
Because I have noticed that COUNT( DISTINCT picture_id ) gives me the correct number of pictures I tried this:
( SUM( vote_value ) / GREATEST( COUNT( DISTINCT picture_id ), 1 ) ) AS score
It works in this example, but what if there were more joins in one query?
Just want to know whether there is a better or more 'elegant' way this problem can be solved. Also I'd like to know whether my solution is MySQL-specific or standard SQL?
This quote from William of Okham applies here:
Enita non sunt multiplicanda praeter necessitatem
(Latin for "entities are not to be multiplied beyond necessity").
You should reconsider why do you need this to be done in a single query? It's true that a single query has less overhead than multiple queries, but if the nature of that single query becomes too complex, both for you to develop, and for the RDBMS to execute, then run separate queries.
Or just use subqueries...
I don't know if this is valid MySQL syntax, but you might be able to do something similar to:
SELECT
gallery.*, a.score, b.pictures
LEFT JOIN
(
select vote_gallery_ref, sum(vote_value) as score
from vote
group by vote_gallery_ref
) a ON gallery_id = vote_gallery_ref
LEFT JOIN
(
select picture_gallery_ref, count(picture_id) as pictures
from picture
group by picture_gallery_ref
) b ON gallery_id = picture_gallery_ref
How often do you add/change vote records?
How often do you add/remove picture records?
How often do you run this query for these totals?
It might be better to create total fields on the gallery table (total_pictures, total_votes, total_vote_values).
When you add or remove a record on the picture table you also update the total on the gallery table. This could be done using triggers on the picture table to automatically update the gallery table. It could also be done using a transaction combining two SQL statements to update the picture table and the gallery table. When you add a record on the picture table increment the total_pictures field on the gallery table. When you delete a record on the picture table decrement the total_pictures field.
Similary when a vote record is added or removed or the vote_value changes you update the total_votes and total_vote_values fields. Adding a record increments the total_votes field and adds vote_values to total_vote_values. Deleting a record decrements the total_votes field and subtracts vote_values from total_vote_values. Updating vote_values on a vote record should also update total_vote_values with the difference (subtract old value, add new value).
Your query now becomes trivial - it's just a straightforward query from the gallery table. But this is at the expense of more complex updates to the picture and vote tables.
As Bill Karwin said, doing this all within one query is pretty ugly.
But, if you have to do it, joining and selecting non-aggregate data with aggregate data requires joining against subqueries (I haven't used SQL that much in the past few years so I actually forgot the proper term for this).
Let's assume your gallery table has additional fields name and state:
select g.gallery_id, g.name, g.state, i.num_pictures, j.sum_vote_values
from gallery g
inner join (
select g.gallery_id, count(p.picture_id) as 'num_pictures'
from gallery g
left join picture p on g.gallery_id = p.picture_gallery_ref
group by g.gallery_id) as i on g.gallery_id = i.gallery_id
left join (
select g.gallery_id, sum(v.vote_value) as 'sum_vote_values'
from gallery g
left join vote v on g.gallery_id = v.vote_gallery_ref
group by g.gallery_id
) as j on g.gallery_id = j.gallery_id
This will yield a result set that looks like:
gallery_id, name, state, num_pictures, sum_vote_values
1, 'Gallery A', 'NJ', 4, 19
2, 'Gallery B', 'NY', 3, 32
3, 'Empty gallery', 'CT', 0,