views:

48

answers:

3

I've got a query that looks like this:

select a.title, is.filename
  from articles a
  join article_images ai on ai.article_id = a.article_id
  join images i on i.image_id = ai.image_id
  join image_sizes is on is.image_id = i.image_id
 where is.size_name = '96x96';

So there is an N:N relationship between articles and images, and an N:1 relationship between images and image sizes. This selects the 96x96 image for each article.

Now I want to change this so it selects the 96x96 image, unless the article_id is 42, in which case it selects a different size. Is there a way to do that in one query?

+4  A: 

Change to this:

where (a.article_id <> 42 AND is.size_name = '96x96')
   OR (a.article_id = 42 AND is.size_name = 'something different')
nickf
This will certainly work, but worth noting that using UNION as suggested in other answers should be slightly faster in MySQL. OR can prevent indexes being used.
Simon
Thanks, this works great. The `UNION` answer is also good, but I'm more interested in readability than efficiency in this case, and this makes more sense to me.
friedo
+1  A: 

I think you should separate your query into two queries: query for 96x96 and query for article_id=42. Then you should UNION this two results. It will also help you to keep your queries clean and readable.

Kirzilla
though it might have better performance, I wouldn't say the query would be cleaner, more readable or easier to maintain...
nickf
+1  A: 
(select a.title, is.filename
  from articles a
  join article_images ai on ai.article_id = a.article_id
  join images i on i.image_id = ai.image_id
  join image_sizes is on is.image_id = i.image_id
 where is.size_name = '96x96' and a.article_id <> 42)
union all
(select a.title, is.filename
  from articles a
  join article_images ai on ai.article_id = a.article_id
  join images i on i.image_id = ai.image_id
  join image_sizes is on is.image_id = i.image_id
 where is.size_name = 'Some other size' and a.article_id = 42)

You will need to replace 'some other size' with whatever the other size is, or use a SELECT TOP 1 and a GROUP BY in the second query if you don't know the size.

Jeremy Sena