tags:

views:

96

answers:

2

I already looked up many posts about this problem (subqueries being very slow in sqlite). but I'm not really good with sql and i don't know what i can do.

i have this query:

SELECT * FROM data d WHERE d.category = 3 AND 
(SELECT COUNT(id) FROM data_tag WHERE data = d.id AND (tag = 2136 OR tag = 8)) >= 2 
ORDER BY id ASC

i have 3 tables data,tag and data_tag (n-m of data and tag) every data has n tags and in this query i search datas by tags (2 tags, both must be in data)

i switched my database from SQL Server to sqlite and besides this query everything works fine. in SQL Server this one took less then 1 sec to execute and in sqlite it takes about 1min. plz give me some tips.

+3  A: 
SELECT d.* FROM data d
INNER JOIN data_tag ON data_tag.data = d.id AND (tag = 2136 OR tag = 8)
WHERE d.category = 3 
GROUP BY d.id
HAVING COUNT(data_tag.id) >= 2 
ORDER BY id ASC
codeholic
Sure that `SELECT *` and `GROUP BY d.id` go together?
Tomalak
In sqlite, yes.
codeholic
Just asking. ;) Not exactly good style (IMO), but if it works.
Tomalak
its working very fine, thank you!execution time : 15.625 ms
+1: Well done, good chap. Pardon my tardiness, ran out of votes.
OMG Ponies
+1  A: 

Try:

  SELECT d.* 
    FROM DATA d 
    JOIN (SELECT dt.data,
                 COUNT(id) AS num_tags
            FROM DATA_TAG dt
           WHERE dt.tag IN (2136, 8)
        GROUP BY dt.data
          HAVING COUNT(id) >= 2) x ON x.data = d.id
ORDER BY d.id 

Don't need ASC in the ORDER BY - that's the default.

OMG Ponies
No need to select `COUNT(id)` since you don't use it anywhere. Also not sure if SQLite can project indexes into temporary tables, a real join might work better.
Tomalak
@Tomalak: Yeah, realized afterwards when I corrected the column alias. Shouldn't negatively affect things though
OMG Ponies
Yeah, it's one line of code, not more. If indexes work is much more interesting.
Tomalak
thank you for ur answer, it works fine, but codeholic's is fasterexecution time for ur query: 31.25ms
@xarfai: Thanks, I appreciate the update!
OMG Ponies