Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite says "no such column: rowid" when using sub-queries

Tags:

sqlite

Here's a query that works fine:

SELECT rowid as msg_rowid, a, b, c FROM messages m1

And here's another one that's also fine:

SELECT rowid as match_rowid FROM messages m2 WHERE x LIKE '%abc%'

But if I put them together as follows, SQLite complains:

SELECT rowid as msg_rowid, a, b, c FROM messages m1
JOIN
    (SELECT rowid as match_rowid FROM messages m2 WHERE x LIKE '%abc%')
ON
    msg_rowid >= match_rowid - 10 AND msg_rowid <= match_rowid + 5

giving what looks like a misleading error message: No such column: rowid.

How can I fix this?

The query runs fine if I use a messages.timestamp field instead of rowid:

SELECT timestamp as msg_ts, a, b, c FROM messages m1
JOIN
    (SELECT timestamp as match_ts FROM messages m2 WHERE x LIKE '%abc%')
ON
    msg_ts >= match_ts - 10 AND msg_ts <= match_ts + 5

Is this a bug, or a by-design restriction on the use of rowid?

like image 503
Roman Starkov Avatar asked Dec 30 '11 17:12

Roman Starkov


1 Answers

Answered by GuZzie in a comment. For some reason SQLite requires me to be explicit about the outer rowid:

SELECT m1.rowid as msg_rowid, a, b, c FROM messages m1
       ^^ HERE
JOIN
    (SELECT rowid as match_rowid FROM messages m2 WHERE x LIKE '%abc%')
ON
    msg_rowid >= match_rowid - 10 AND msg_rowid <= match_rowid + 5
like image 104
Roman Starkov Avatar answered Sep 17 '22 22:09

Roman Starkov