tags:

views:

31

answers:

2

Hi all. I have following 2 tables

Channels:
Id int PK
Title varchar

SubChannels:
ChannelId int
SubchannelId int

When I receive data from service I'm trying to persist it to SQL. I receive a few Channel instance, so I store it in Channels table, after that I'm trying to persist every subchannel (every channel contains list of subchannels), so, I store subchannels in the same table Channels, and store theirs Ids to SubChannel table in following way: ChannelId - SubChannelId.

So, I need to get this tree of channels with one query I'm trying to do this with this query:

 SELECT * FROM Channels 
 EXCEPT 
 SELECT Channels.Id, Channels.Title 
 FROM Channels INNER JOIN SubChannels 
 ON Channels.Id = SubChannels.SubchannelId

But I doesn't work correctly. Using MSSQL it works fine, but in my SQLite something is going wrong.

Could you please help me with this query, or advice me some other solution to store this tree in SQL.

My Channel class looks like this:

int Id
string Title
List<Channel> SubChannels

Thanks in advance

A: 

SQLite does not support EXCEPT

So you may try:

SELECT * FROM Channels  c1
WHERE NOT EXISTS(SELECT 1 
      SELECT Channels.Id, Channels.Title 
      FROM Channels c2 INNER JOIN SubChannels 
      ON Channels.Id = SubChannels.SubchannelId
      WHERE c1.Id = c2.Id
        AND c1.Title =c.Title)
Michael Pakhantsov
[SQLite supports EXCEPT](http://www.sqlite.org/syntaxdiagrams.html#compound-operator).
Benoit
+1  A: 

Could you try:

SELECT Id, Title
  FROM Channels
EXCEPT 
SELECT Channels.Id, Channels.Title
  FROM Channels
 INNER JOIN SubChannels
    ON Channels.Id = SubChannels.SubchannelId

(ie, not selecting *)

A way to optimize it:

SELECT Id, Title
  FROM Channels
 WHERE Id NOT IN (
       SELECT DISTINCT SubchannelId
         FROM SubChannels
    )
Benoit
sqlite supports *
Jeff Norman
yes, but I am not sure it supports EXCEPTING named columns from *, and forgeing such a query is dangerous, if your structure evolves.
Benoit
thanks, without selecting * it works fine. Thanks a lot
Vitali Fokin
I have no idea about SQLite, but after googling for EXCEPT I got this: "Microsoft introduced the EXCEPT operator in SQL Server 2005, which returns all of the distinct(!) rows from the left side of the EXCEPT operator. It also removes all of the rows from the result set that match the rows that are on the right side of the EXCEPT operator." So I would have written it the way you did in your second approach, but I would have added a "distinct" in the first row, like "SELECT DISTINCT Id, Title ..."
tombom