views:

158

answers:

4

Hi all, I am storing pages for websites in a 'pages' database table, they are referenced by their path (i.e. 'articles/my-first-blog-post'), I need to select all the children of a particular page, but without selecting grandchildren.

So if I run:

SELECT * FROM pages WHERE path LIKE 'articles%'

I'll get pages with the following paths:

articles/one
articles/two
articles/two/more
articles/three
articles/three/more/even-more

I need to filter them (in the query) to just:

articles/one
articles/two
articles/three

Is there anyway to do something like:

SELECT * FROM pages WHERE path LIKE 'articles%' AND path NOT LIKE 'articles%/%'

Any ideas? Cheers.

+2  A: 

If your files have file extensions this will work:

   SELECT * FROM pages 
    WHERE path LIKE 'articles%' 
      AND SUBSTRING_INDEX(path,'/',2) LIKE '%.file_extension';

otherwise:

   SELECT * FROM pages 
    WHERE path LIKE 'articles%' 
      AND SUBSTRING_INDEX(path,'/',2)=SUBSTRING_INDEX(path,'/',3)=;
dnagirl
This would have worked, apart from I'd have to calculate the number of forward slashes each time, so it's more complicated than the regexp suggestion. Thanks nonetheless.
Ryan Townsend
+2  A: 

You can use regular expressions for that. The keyword REGEXP works both for mysql and sqlite:

... WHERE path REGEXP '^articles/[^/]+'
soulmerge
This seems like the best way, but I'm getting the following error:SQLite3::SQLException: no such function: REGEXPDo I need to install an addon or something? I'm using Mac OS Snow Leopard, SQLite is just for dev, MySQL for production, so if it's just an addon that's no problem.
Ryan Townsend
Looks like I just need an addon for the Ruby implementation. Your suggestion worked perfectly, cheers.
Ryan Townsend
A: 
SELECT * FROM pages WHERE path LIKE "%/%" AND path NOT LIKE "%/%/%";

works for me at least.

Kimvais
+1  A: 

Hi

Using regular expressions (LIKE clause or REGEXP) may incur severe performance problems in SQLite because they require full table scan. Read more about this in http://web.utk.edu/~jplyon/sqlite/SQLite_optimization_FAQ.html.

You can use inequality operators (like < and >) to increase performance (if the relevant column has an index).

Liron Levi (author of SQLite Compare diff/merge tool)

Liron Levi
I only use SQLite for development, MySQL in production, so this isn't an issue. Thanks for the heads up though.
Ryan Townsend