samedi 23 mai 2015

How do you SELECT items based on COUNT(*) from another table? - SQLite

My tables are like so:

Tile

  • Id

TestSet

  • Id
  • TileId
  • CreatedAt
  • Outcome (boolean)

There is a 1:n relationship between Tile and TestSet.

I want to get the tiles that have a testSet with a true Outcome value on the most recent testSet (ordered by the CreatedAt column). My first attempt at it doesn't work as I want it to.

SELECT * FROM Tile
JOIN (SELECT TileId FROM (SELECT * FROM TestSet
WHERE tileId == 'Tile1'
ORDER BY __createdAt DESC
LIMIT 1)
WHERE Outcome=1) as ts ON ts.TileId == Tile.id;

The problem with the above statement is that the WHERE clause in the most inner SELECT statement is hardcoded.

Here's how I broke up the process:

  1. Grab the most recent testSet.
  2. SELECT only the tileId column from that testSet.
  3. JOIN the tile table on the above statements to get a list of all the tiles.

I feel like I'm thinking about this the wrong way and I shouldn't really be doing a JOIN. But I don't have enough SQL experience to know exactly how to go about this problem. I'm using SQLite specifically in a mobile app, so are there any SQLite statements that can help me get the correct set of tiles?

Aucun commentaire:

Enregistrer un commentaire