Complex sqlite query, what's the correct syntax? - sqlite

The query is this one:
SELECT FriendID FROM Relationships WHERE UserID = 1
INTERSECT
(SELECT FriendID FROM Relationships WHERE UserID = 2
UNION SELECT UserID FROM Relationships WHERE FriendID = 2)
(for the curious readers, please note that the friend relationship is not necessarily symmetrical in this scenario)
I've tried all the possible combination of parentheses with no luck.
If I omit the parentheses, there's no operator precedence in the sense that it reads it like 5+6*3 = 33, so if I put the union before the intersection, the query works fine. But what will I do when I will have to intersect two unions?

You can use temporary tables in such case.

Thanks to Larry Lustig (which pointed me this), I rewrote my query as follows
SELECT FriendID FROM Relationships WHERE UserID = 1
INTERSECT SELECT ID FROM
(SELECT FriendID AS ID FROM Relationships WHERE UserID = 2
UNION SELECT UserID AS ID FROM Relationships WHERE FriendID = 2)
And it works.

Related

Query to find 'most watched' [COUNT()] from one table while returning the results from another

The question probably is quite confusing.
In affect i have the following:
WatchList table
UserId | FilmId
| 3 77
| etc etc
|
|
|
these are foreign keys for the following tables
FilmDB - Film_title, Film_plot, Film_Id etc.
and
aspnet_memberships - UserId, Username etc..
Now, i presume i will need to use a join but i am struggling with the syntax.
I would like to use 'Count' on the 'WatchList' and return the most frequent filmId's and their counterpart information, but i'd then like to return the REST of the FilmDB results, essentially giving me a list of ALL films, but with those found in the WatchedList my frequently sorted to the top.
Does that make sense? Thanks.
SELECT *
FROM filmdb
LEFT JOIN (
SELECT filmid, count(*) AS cnt
FROM watch_list
GROUP BY filmid) AS a
ON filmdb.film_id = a.filmid
ORDER BY isnull(cnt, 0) DESC;
http://sqlfiddle.com/#!3/46b16/10
You did not specify if the query should be grouped by film_id or user_id. The example I have provided is grouped by user if you change that to film_id then you will get the watch count for all users per film.
You need to use a subquery to get the count and then order the results by the count descending to get an ordered list.
SELECT
*
FROM
(
SELECT
WatchList.Film_Id,
WatchCount=COUNT(*)
FilmDB.Film_Title
FROM
WatchList
INNER JOIN FilmDB ON FilmDB.Film_Id=WatchList.Film_Id
GROUP BY
WatchList.UserID,
WatchList.Film_Id,
FilmDB.Film_Title
)AS X
ORDER BY
WatchCount DESC

Enhance current SQLite query

I inherited an old SQLite database I should not change (this is a requirement). There are many tables, but I will focus on two of them:
songs
----------
song_id (primary autoincrement)
group_id (external)
title
audio_file_path
wasPurchased (boolean, 0/1)
groups
----------
group_id (primary autoincrement, related to songs group_id)
group_name
At the moment, the application needs to perform this query:
SELECT song_id,title,audio_file_path,wasPurchased,G.group_name AS groupName,
G.group_id AS groupId FROM songs AS S JOIN groups AS G ON S.group_id=G.group_id
ORDER BY groupName DESC
Is there any way, with the same query, to extract how many distinct G.group_id have wasPurchased=0?
Any help is appreciated.
SELECT song_id,title,audio_file_path,wasPurchased,
G.group_name AS groupName, G.group_id AS groupId,
SUM (SELECT DISTINCT g.group_id
FROM yourtables/JOIN
WHERE wasPurchased = 0) as nb
FROM songs AS S
JOIN groups AS G ON S.group_id=G.group_id
ORDER BY groupName DESC
Not sure if it's the best way(never tried a select in a sum but...), but I think it will help you.

Creating a VIEW from multiple tables each with a different number of columns

I want to combine multiple tables into one VIEW.
My understanding is that if the number of columns are different we cannot use UNION.
How do I solve this?
I have the following three TABLES:
1.Table Name- Albums
2.Table Name-AlbumPictures
3.Table Name-Stories
I want to have 3 tables as follows:(i can do this part using INNER JOINS- kindly correct me if i am wrong)
For Stories: StoryID,AlbumID,StoryTitle,AlbumCover,Votes
For Albums: AlbumID,AlbumName,AlbumCover,Votes
For Pictures: AlbumPictureID,Votes
I want to merge all the rows retrieved from the above queries into one VIEWand shuffle them. As the number of columns are different in each of the result sets above am I able to combine them into one VIEW?
So in your UNION sql, either remove the extra columns from the sql for the table with too many, or add extra columns with constant default values to the sql for the table with fewer columns.
Based on your example output, adding extra constant values might look like this...
Select StoryID id, AlbumID,
StoryTitle name, AlbumCover, Votes
From Stories
UNION
Select AlbumID id, AlbumID,
AlbumName name, AlbumCover, Votes
From Albums
UNION
Select AlbumPictureID id, null AlbumId,
null AlbumCover, Votes
From pictures
Order By id, Votes, name
But this makes me want to ask WHY???
EDIT: To sort, just add an order by using output column names, as shown above....
In order to use a UNION or UNION ALL operator, the number of columns and datatypes of the columns returned by each query have to be the same.
One trick you can use is to return a NULL value for the columns that are "missing" from some of the queries.
For performance, I recommend you use the UNION ALL operator in place of the UNION operator, if removing duplicates is not a requirement.
Whenever I need to do something like this, I usually include a literal in each query, as an identifier of which query the row came from.
e.g.
SELECT 'a' AS source
, a.id AS id
, a.name AS name
FROM table_a a
UNION ALL
SELECT 'b' AS source
, b.id AS id
, NULL AS name
FROM table_b b
ORDER BY 1,2
You can do something like this. All three tables are given similar columns with null values and TableName column is to identify the table which brings the data
EDIT: I have to say, this is not the right approach. I wanted to show you how to union tables but I think now it is getting ugly when editing it according to your comments.
--Note: Vote is on all three table, I have selected from Stories
select s.storyId, a.albumId, s.storyTitle, null albumName,
ap.albumCover, s.votes , null albumPictureId, 'stories-albums-albumPics' tableName
from Stories s join Albums a on s.albumId = a.albumId
join AlbumPictures ap on a.albumid = ap.albumId
UNION ALL
select null storyId, a.albumID, null storyTitle, a.albumName,
ap.albumCover, a.votes, null albumPictureId, 'albums-albumPics' tableName
from Albums a join AlbumPictures ap on a.albumid = ap.albumId
UNION ALL --use required table here as well
select null storyId, null albumId, null storyTitle, null albumName,
null albumCover, votes, albumPictureId, 'pictures' tableName
from Pictures
I guess this makes little sense,
Select StoryID+'SID' id, AlbumID,
StoryTitle name, AlbumCover, Votes
From Stories
UNION
Select AlbumID+'AID' id, AlbumID,
AlbumName name, AlbumCover, Votes
From Albums
UNION
Select AlbumPictureID+'APID' id, null AlbumId,
null AlbumCover, Votes
From pictures
Concatenating 'SID','AID' and 'APID' and it will make some sense when you see UI data
select * from Stories as s
inner join Albums as a on a.AccountID = s.AccountID
inner join Pictures as p on p.AccountID = s.AccountID
will return all, as long as AccountID is defined in all 3 tables
To only obtain the unique columns change * for the columns you desire
Why on earth would you need the data to be all in the same view? Just return 3 sets of data. If for example you are using a web browser as the front end, you could perform three queries and return them as a single set of JSON, for example:
{
Albums: [
{AlbumID: 1, AlbumName: 'blah', ... },
{AlbumID: 2, AlbumName: 'gorp', ... }
],
AlbumPictures: [
{AlbumID: 1, URL: 'http://fun.jpg'},
{AlbumID: 1, URL: 'http://fun2.jpg'}
],
Stories [
{StoryID: 3, StoryTitle: 'Jack & Jill', ... },
{ etc. }
]
}
There is absolutely no programming architectural constraint forcing you to put everything together in a single view.

Please help me with this traversing query

CatID parID catName
1 -1 A
2 1 B
3 2 C
4 3 D
I want to write a query which returns the parent child relationship in string format.
In the above table the catName has parentId -1, which means it has got no parent. B has parentID 1, which means that A is its parent.
So finaly the string is like this
A=>B=>c=>D
This is the way I want to generate a query.
I'll pass CatID, and it will traverse until it gets a -1.
declare #CatID int;
set #CatID = 4;
with C as
(
select parID,
cast(catName as varchar(max)) as catName
from YourTable
where CatID = #CatID
union all
select T.parID,
T.catName + '=>' + C.catName
from YourTable as T
inner join C
on T.CatID = C.parID
)
select catName
from C
where parID = -1
SE-Data
As a partial answer, it sounds like you need a recursive query. Here is a StackOverflow thread with some good information on recursive queries. As to how to use a query to turn it into a single string, I don't know... that part may be more optimized for a programming language.
you need to define function then call it in recursive loop.
You can use MPTT (Modified Preorder Tree Traversal) to store nested tree or hierarchical data.
this article describe how to get hierarchical "breadcrumb" within a single query.

Linq to Entities: Left join to get items NOT found in the join

I've got two un-related (no FK's defined) tables. The first table contains some tasks for which a user may not have access. I need to find all those tasks - in this case, the joined table would contain nulls. How do I get them?
Here's the setup:
TimeData table
- userID
- taskID
- hours
ApprovedTasks table (the one that should contain nulls)
- taskID
- userID
The SQL query would look like this:
select * from TimeData td
left join ApprovedTasks at
on at.taskID = td.taskID and at.userID = td.userID
where at.taskID is null
Any way to pull that off using a LINQ to Entity query?
TIA
Check out... Disjoint Union in LINQ
This should work...
var approvedTaks = from at in ApprovedTasks.Except(
from at2 in ApprovedTasks
where at2.userID == userId and at2.taskID==taskId
select at2)
where at.userID == userId and at.taskID==taskId
select at;
but sorry don't have the database handy to test it.

Resources