How to return result set based on other rows

Posted by understack on Stack Overflow See other posts from Stack Overflow or by understack
Published on 2010-05-05T20:43:23Z Indexed on 2010/05/05 20:48 UTC
Read the original article Hit count: 167

Filed under:

I've 2 tables - packages and items. Items table contains all items belonging to the packages along with location information. Like this:

Packages table
id, name, type(enum{general,special})
1, name1, general
2, name2, special

Items table
id, package_id, location
1, 1, America
2, 1, Africa
3, 1, Europe
4, 2, Europe

Question: I want to find all 'special' packages belonging to a location and if no special package is found then it should return 'general' packages belonging to same location.

So,

  1. for 'Europe' : package 2 should be returned since it is special package (Though package 1 also belongs to Europe but not required since its a general package)

  2. for 'America' : package 1 should be returned since there are no special packages

© Stack Overflow or respective owner

Related posts about mysql