1

I have a table in mysql in this structure

table: member

| Id | Name | Lastname | Username 
| --------------------------------
| 1  | Alexi| Lalas    | alexi
| 2  | Jack | Louis    | louis

And I have a table called member images with this structre:

table: image

| Id | MemberId | Image      | Type  |
|------------------------------------|
| 50 | 1        | face.jpg   |Avetar |
| 51 | 1        | image.jpg  |Gallery|
| 52 | 2        | main.jpg   |Avetar |
| 53 | 2        | jungle.jpg |Gallery|

And I want to get this result

| Id | Name | Lastname | Username | Image1   | Image2   |
|-------------------------------------------------------|
| 1  | Alexi| Lalas    | alexi    |face.jpg  |image.jpg |
| 2  | Jack | Louis    | louis    |main.jpg  |jungle.jpg|

Becuase of some reasons I can't handle is on app side and I have to do it on sql side. Imagin that I always have 2 type of images and we always have Image1 and Image2.

Any help would be appritiated.

2
  • 1
    The keyword you're after is JOIN: w3schools.com/sql/sql_join.asp Commented Dec 15, 2013 at 13:18
  • @TasosBitsios No, he wants a pivot, not a join. Commented Dec 15, 2013 at 13:39

2 Answers 2

2

Since they are only two types, you can use the CASE expression to do so. Something like this:

SELECT
  m.Id,
  m.Name,
  m.LastName, 
  m.UserName,
  MAX(CASE WHEN i.Type = 'Avetar' THEN i.Image END) AS 'Image1',
  MAX(CASE WHEN i.Type ='Gallery' THEN i.Image END) AS 'Image2'
FROM member AS m
LEFT JOIN image AS i ON m.Id = i.MemberId
GROUP BY m.Id,
         m.Name,
         m.LastName, 
         m.UserName;

Note that: LEFT JOIN will include all the members from the member table even if they have no images in the image table, in this case NULL will be returned.

See it in action here:

Sign up to request clarification or add additional context in comments.

Comments

0

The way to do this is via a subselect (subquery). You would subselect the first column as the image for the user withe Avetar type and the other column subselect would be for the image with the type Gallery. If you can't find a way to make User ID and Type unique in your sub table then you are going to have issues with this type of query. Keep in mind that a subselects can impact performance heavily.

http://dev.mysql.com/doc/refman/5.0/en/subqueries.html

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.