1

I need to construct a SQLite statement based on the below table schema. The ParentEventInfoID is mapping to other items in the same table.

Table Name EventInfo: _id, Name, Description, ParentEventInfoID, SortId

Part of the requirements for the query needs perform a where clause on Name and Description, which I don't have a problem with:

SELECT * FROM EventInfo 
   Where Name LIKE "%search text%" OR 
         Description LIKE "%search text%" 
ORDER BY SortId;

The part i'm having trouble with is I need to also include the parent item for an entry. Below is a statement that returns all the matches for the LIKE's, but only one parent item even though I know I should have more:

SELECT * FROM EventInfo 
    Where Name LIKE "%search text%" OR 
          Description LIKE "%search text%" OR 
          _id = (SELECT ParentEventInfoID FROM EventInfo
                   Where (Name LIKE "%search text%" OR 
                          Description LIKE "%search text%") 
ORDER BY SortId

I haven't done a ton of SQL in a while and I'm feeling very rusty. Any help is greatly appreciated. Thanks!

4
  • 2
    replace the = after _id with IN
    – Miller
    Jan 29, 2014 at 4:30
  • @MillerKoijam That did the trick! Do you think this is the most efficient way to build like this?
    – KevinM
    Jan 29, 2014 at 4:38
  • 1
    There should be better query. I think we can avoid the like clause in the inner query as we are hitting the same table
    – Miller
    Jan 29, 2014 at 4:41
  • Yeah that's the part I don't like. Seem redundant. But in the meantime your solution got it working for me. If you want to put it as an answer I'll accept it?
    – KevinM
    Jan 29, 2014 at 4:44

2 Answers 2

1

Try this

SELECT * FROM EventInfo 
    Where Name LIKE "%search text%" OR 
          Description LIKE "%search text%" OR 
          _id IN (SELECT ParentEventInfoID FROM EventInfo
                   Where (Name LIKE "%search text%" OR 
                          Description LIKE "%search text%") 
ORDER BY SortId

But there should be better query that avoid like clause in the inner query.

1
  • Perfect. Thanks for the help. I would like to find a more efficient statement, but this keeps me going. Thanks again!
    – KevinM
    Jan 29, 2014 at 4:55
0

You can use SELF JOINS

SELECT E1.* FROM EventInfo E1
LEFT JOIN EventInfo E2
ON E1._id =E2.ParentEventInfoID 
Where Name LIKE "%search text%" OR 
      Description LIKE "%search text%" OR  
ORDER BY E1.SortId
1
  • Thanks for the quick reply. I just tried this and it ends up with the same result as my first statement with out the inner select.
    – KevinM
    Jan 29, 2014 at 4:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.