posted 16 years ago
Hi there,
I'm working on an application that will register when users see particular things. Some of the database is outlined below:
User: id, name
Catalog: id, name
CatalogItem: id, name, catalog_id
Spotted: user_id, catalog_item_id, spotted_date
So, a Catalog is a collection of CatalogItems (eg, Planes would contain 747, 767, DC10, etc). Spotted registers when an individual user has seen one of the CatalogItems. What I was hoping to do was put together a query that returns me a list of all the CatalogItems with the date spotted, if it had been. The closest I've got is the following:
(SELECT `catalog_item`.`id`, `catalog_item`.`name`, `spied`.`spied` FROM `user`, `catalog`, `catalog_item`, `spied` WHERE`user`.`id` = 3 AND `spied`.`user_id` = `user`.`id` AND `spied`.`catalog_item_id` = `catalog_item`.`id` AND `catalog_item`.`catalog_id` = `catalog`.`id` AND`catalog`.`id` = 1)
UNION
(SELECT `catalog_item`.`id`, `catalog_item`.`name`, 'xxx' as spied FROM `catalog`, `catalog_item` WHERE`catalog_item`.`catalog_id` = `catalog`.`id` AND `catalog`.`id` = 1)
ORDER BY `name`
That seems a bit heavy handed and would still leave me having to filter out the duplicate (items that have been spotted from the second sub-query) in some code.
It feels like an outer join should be the order of the day, but I've tried and I can't write one correctly that (left?) outer joins CatalogItem and Spotted, and maintains the rest of the conditions. Everything I've tried is syntactically wrong, rather than returning wrong data. Can anyone point me in the right direction? I'm using MySql if that makes a difference.
Outer joins have always confused me a bit!
Cheers
[ May 07, 2007: Message edited by: Andy Westley ]