Using querys to get information from different tables - sqlite

I am learning SQLite and I'm using this database to learn how to correctly use querys but I'm struggling specially when I have to use data from multiple tables to get some information.
For example, with the given database, is there a way to get the first name, last name and the name of songs that every customer has bought?

All you have to do is a simple SQL SELECT query. When you say you're having trouble getting it from multiple tables, I'm not sure if you're trying to get the data from all of the tables in one single query, as that is not necessary. You just need to have multiple instances of the SELECT query, just for different tables (and different column names).
SELECT firstName, lastName, songName FROM table_name

You have to study about JOINS:
select
c.FirstName,
c.LastName,
t.Name
from invoice_items ii
inner join tracks t on t.trackid = ii.trackid
inner join invoices i on i.invoiceid = ii.invoiceid
inner join customers c on c.customerid = i.customerid
In this query there are 4 tables involved and the diagram in the link you posted, shows exactly their relationships.
So you start from the table invoice_items where you find the bought songs and join the other 3 tables by providing the columns on which the join will be set.
One more useful thing to remember: aliases for tables (like c for customers) and if needed for columns also.

You need to use joins to get data from multiple tables. In this case I'd recommend you using inner joins.
In case your are not familiar with joins, this is a very good article that explains the different types of joins supported in SQLite.
SQLite INNER JOINS return all rows from multiple tables where the join
condition is met.
This query will return the first and last name of customers, and the tracks they purchased.
select customers.FirstName,
customers.LastName,
tracks.name as PurchasedTracks from invoice_items
inner join invoices on invoices.InvoiceId = invoice_items.InvoiceId
inner join customers on invoices.CustomerId = customers.CustomerId
inner join tracks on invoice_items.TrackId = tracks.TrackId
order by customers.LastName

Related

How are you supposed to think of joins in cosmosdb?

I am very confused by the cosmosdb documentation on joins. When I think of a join conventionally, I think of 2 tables, with 1 shared id, on which I perform the join. These 2 tables have different schemas, but the result of the join is a combined table with a merge of the columns from both tables. The join for cosmosdb does not seem to me intuitively congruent with that.
I have a collection with heterogenous data. Each document can have a different structure from the next. I want to count the number of documents that have a value that is present in the result set of a subquery. Intuitively, I want to do something like this:
SELECT COUNT(1) as c
FROM CollectionName as outer
where outer.type = "table"
JOIN ((SELECT c.id from c where c.type = "database") as inner) on outer.databaseId == t.id
// count the number of tables that are in deleted databases
It would seem like I would need to do a join on the result of the subquery with the result of the outer query, and then process that resulting table. But I am not understanding right now how to do that:
Select COUNT(1)
from Collection outer
where outer.type = 'table'
JOIN (select c.id from c IN outer.databaseId where c.type = "database" and c.state = "deleted")
I am constantly getting a 400 with the above query. So how am I supposed to think about joins in cosmosdb?
Cosmos is a document database. It stores and operates on json data which can be in hierarchical format. Joins in Cosmos reference tuples within these hierarchies where they can be projected with other data in the document.
There is a really good article that talks through this at pretty deep level but also have lots of examples too, Joins in Cosmos DB.
This takes some getting used to writing queries like this but once you get the hang of it you'll be ok. You can easily practice queries using the Query Playground that has a bunch of sample queries for nutrition dataset with food and ingredients. Or follow along with the families data in the docs. You can create additional items and then write some queries to see how joins work.
Hope that is helpful.

T-SQL: Select foreign key from one table and find corresponding rows in another

I have two tables: tblA contains a foreign key which I want to use to pull corresponding rows from tblB. The following queries will not work, but they explain what I want to do:
SELECT [MyID]
FROM [tblA]
SELECT [MyColumn]
FROM [tblB]
WHERE [ID] = [tblA].[MyID]
This should be a fairly simple query but I am a noob with T-SQL.
Use a JOIN:
SELECT A.MyID, B.MyColumn
FROM tblA A INNER JOIN tblB B
ON A.MyID= B.ID
There are different types of joins, the INNER JOIN returns only rows from tblA with a matching key in tblB.

How to query a query result?

I created query to fetch top selling products. Now, I want to query this result, for example, top 100 products order by SerialNo or top 100 products order by SellingQty... etc..
Here is my query which give all products order by totalOrders :
SELECT tblProducts.skuCode,tblProducts.productCode, tblProducts.productName, COUNT(tblOrders_Products.delivered) as totalOrder
FROM tblOrders_Products INNER JOIN tblProducts ON tblOrders_Products.productID = tblProducts.productID
WHERE tblProducts.productName is not null
GROUP BY tblOrders_Products.delivered, tblOrders_Products.productID, tblProducts.skuCode, tblProducts.productName,tblProducts.productCode
ORDER BY totalOrder
I considered to create a view. But many posts are telling that, using Order By clause with view, is harmful or not give result sometime, So, I am wondering how this can be done?
I can do this in .NET by sorting DataTable, and using that as DataSource. But how it can be done in SQL SERVER?
And which way is faster? Ordering in SQL Server or in DataTable?
I am using SQL SERVER 2005.
Thanks.
This should give you the Top 100 products ordered by SerialNo (I assumed it was a part of tblProducts here).
You can switch the Order By parameter to get it ordered the other fields.
SELECT a.skuCode, a.productCode, a.productName, a.totalOrder, a.SerialNo
FROM
(
SELECT TOP 100 tblProducts.skuCode,tblProducts.productCode, tblProducts.productName, COUNT(tblOrders_Products.delivered) as totalOrder, tblProducts.SerialNo
FROM tblOrders_Products INNER JOIN tblProducts ON tblOrders_Products.productID = tblProducts.productID
WHERE tblProducts.productName is not null
GROUP BY tblOrders_Products.delivered, tblOrders_Products.productID, tblProducts.skuCode, tblProducts.productName,tblProducts.productCode
ORDER BY totalOrder) a
ORDER BY a.SerialNo
Something like this should do it:
WITH TopProducts AS
(
SELECT TOP 100 tblProducts.productID, COUNT(tblOrders_Products.delivered) as totalOrder
FROM tblOrders_Products INNER JOIN tblProducts ON tblOrders_Products.productID = tblProducts.productID
WHERE tblProducts.productName is not null
GROUP BY tblProducts.productID
ORDER BY COUNT(tblOrders_Products.delivered) DESC
)
SELECT *
FROM TopProducts INNER JOIN tblProducts ON TopProducts.productID = tblProducts.productID
ORDER BY tblProducts.SerialNo
The TopProducts is called a Common Table Expression in SQL Server, and it's a neat way to reuse query parts.
Sorting a DataTable in .NET will woks as well. You will probably not notice any difference in performance for only 100 rows. Sorting on the client would actually be preferrable in a scenario when the user may want to sort the results in different ways, e.g. by clicking column headers in a grid, since this can be accomplished without a separate database call.

Combining data from two SQL queries

I'm porting my app from Django to ASP.NET Webforms (against my will, but what can we do with the corporate world..), and I'm used to Django generating all my SQL queries so now I need help.
I have 3 tables: proceso,marcador,marcador_progreso
Every proceso has many marcador_progreso, which in turn is the foreign key table to marcador.
So basically the tables look like:
proceso
id
marcador
id
text
marcador_progreso
id
marcador_id
proceso_id
state
For all the marcador_progreso where its proceso_id is the current proceso (from a QueryField in the URL), I need to list its state and it's respective marcador.text.
I've been working with EntityFramework but this is like a double query so I'm not sure how to do it.
I guess it is something that combines the following two statements, but I'm not sure how to do it.
SELECT [state] FROM [marcador_progreso]
SELECT [text] FROM [marcador] WHERE ([id] = marcador_id)
You want to do a JOIN:
SELECT mp.state, m.text
FROM marcador_progreso as mp
INNER JOIN marcador as m
ON mp.marcador_id = m.id
This is an excellent post that goes over the various join types.
You'll want to know about JOINs to call more than one table in your FROM clause. JOIN combines records from two or more tables in a database by using values common to each. There are different types - the SQL example below is an INNER join, which gets only records where both of the tables have a match on the common value. You may want to consider a LEFT join which would get any records that exist for the LEFT table (in this case marcador), even if there are not any matching record in the RIGHT(marcador_progreso ) table.
Pop the below in Management Studio, Play with different joins. Replace the INNER with LEFT, run it without the WHERE.
Read about `JOIN's.
In general, for your new venture of writing your own queries, they all start with the same basic structure:
SELECT (UPDATE,WHATEVER DML statement, etc) (COLUMNS) what you want to display (update,etc)
FROM (TABLE) where those records live
WHERE (FILTER/LIMIT) conditions that must be met by the data
Happy fetching!
SQL:
DECLARE #ProcessoId int
SET #ProcessoId = --1
SELECT m.[STATE],mp.[TEXT]
FROM marcador M
INNER JOIN marcador_progreso MP ON MP.marcador_id = m.id
WHERE proceso_id = #ProcessoId
EF INNER example
var marc = from m in yourcontext.marcador
join mp in yourcontext.marcador_progreso on m.id equals mp.marcador_id
where proceso_id == processoIdvariable
EF LEFT example
var marc = from m in yourcontext.marcador
join mp in yourcontext.marcador_progreso on m.id equals mp.marcador_id into details
from d in details.DefaultIfEmpty()
where proceso_id == processoIdvariable

SQL Server Creating Indexes Catalogs with joined tables

So at the moment I am building a Advanced Search in .NET, and getting the results is just proving a bit slow so was looking at creating indexes on the tables.
I.e went to tables and define full text index.
So now I have my catalog with the 5 tables and selected columns.
But I cant see how this catalog actually joins these tables ?
I.e. in my "slow" stored procedure I could have
select *
from table1
inner join table2 ON table1.id = table2.linkedID
etc for other tables ?
and now I guess I can go
select * from catalogName
but how does catalogName know what columns to join for the inner join etc
You don't query the fultext catalog directly, you use the fulltext functions in your query, like CONTAINS, CONTAINSTABLE, FREETEXT and FREETEXTTABLE:
SELECT field, field, field
FROM table
WHERE CONTAINS(field, 'some text');
Full text has nothing to do with joining tables and if your query is slow because you join 5 tables then FT is unlikely to help at all.

Resources