1

I have this type of query

SELECT one, two, three FROM (
  ( SELECT data AS one FROM thetable WHERE `id` = '$id' AND name = 'one') t1,
  ( SELECT data AS two FROM thetable WHERE `id` = '$id' AND name = 'two') t2,  
  ( SELECT data AS three FROM thetable WHERE `id` = '$id' AND name = 'three') t3
)

and when one of the row is missing for a certain id, it just skips all of the selects related to the id.

I'm hoping to get something like this:

id:24     one:somedata      two:somedata      three:somedata
id:25     one:somedata      two:EMPTY         three:somedata
id:26     one:somedata      two:somedata      three:somedata
id:27     one:EMPTY         two:somedata      three:somedata

but I'm getting:

id:24     one:somedata      two:somedata      three:somedata
id:25     one:EMPTY         two:EMPTY         three:EMPTY
id:26     one:somedata      two:somedata      three:somedata
id:27     one:EMPTY         two:EMPTY         three:EMPTY

Why?

2
  • 2
    Please use proper JOIN. It's been around for over 25 years!!! Commented Jul 3, 2020 at 18:13
  • @Eric can you elaborate, please? What do you mean exactly? Commented Jul 3, 2020 at 19:13

1 Answer 1

2

You can try the below way -

select id,
max(case when  name = 'one' then data end) as one,
max(case when  name = 'two' then data end) as two,
max(case when  name = 'three' then data end) as three
from thetable where `id` = '$id'
group by id
Sign up to request clarification or add additional context in comments.

3 Comments

You probably want to move the condition id = '$id' to the WHERE-clause so the query can use an index on id.
@slaakso, yes you are right, thank you for pointing it out
Wow, thank you! It works, and it works 10 times faster! Why is that? It takes 3 seconds to finish the query, whereas my query was taking 30 seconds to complete.

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.