/    Sign up×
Community /Pin to ProfileBookmark

MySQL query to find rows where previous and following IDs are empty

Hello,

It’s been a while since I’ve been on WebDeveloper.com, but I’ve decided to come back with a seemingly complex question about a highly customized MySQL query.

It’s best to illustrate my problem with a simplified example. Say I have a table, TestTable, with two fields, ItemID and NameID:

[code]+——–+——–+
| ItemID | NameID |
+——–+——–+
| 1 | 0 |
| 2 | 0 |
| 3 | 4 |
| 4 | 0 |
| 5 | 0 |
| 6 | 2 |
| 7 | 0 |
| 8 | 0 |
| 9 | 0 |
| 10 | 3 |
| 11 | 0 |
| 12 | 1 |
| 13 | 0 |
| 14 | 0 |
| 15 | 0 |
+——–+——–+[/code]

What I need is a query that selects all rows [i]where NameID is 0 in the current, previous, and following rows[/i]. For example, using the table above, the query should return rows 1, 8, 14, and 15.

I cams up with the query below, but it doesn’t work, and even if it did, it would take a lot of processing power because of the subquery:

[code]SELECT * FROM TestTable WHERE 0 = ALL (SELECT NameID FROM TestTable WHERE ItemID>=ItemID-1 AND ItemID<=ItemID+1)[/code]

In my actual application, I will actually be performing this query on [i]two[/i] columns in a table that might include tens of thousands of rows at a given time. I know that it might be easier to pull the table (or even part of it) into PHP and do the processing there, but this might not be plausible since it would probably need to pull thousands of rows at a time.

Any ideas? Thanks in advance.

to post a comment
PHP

1 Comments(s)

Copy linkTweet thisAlerts:
@shane_carrauthorJun 20.2009 — I found a way around my problem by using a table to keep track of certain "sections" to be filled to bring fewer rows into PHP for analyzing ?
×

Success!

Help @shane_carr spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...