Tuesday 4 September 2018

Mysql JOIN Query does not return the expected results

2I know I am having a simple issue .. But I cannot for the life of me solve it .. Here is what I am trying to do. I have 3 tables and some sample data:

customer_entity_varchar
  entity_id    attribute_id        value

   '2'             '5'             'John'
   '2'             '7'             'Smith'
   '2'             '336'           'ADELANTO'
   '3'             '5'             'Jane'
   '3'             '7'             'Doe'
   '3'             '336'           'ADELANTO'
   '4'             '5'             'Peter'
   '4'             '7'             'Griffin'
   '4'             '336'           'Not ADELANTO'

customer_entity
  entity_id        email 

   '2'             'jsmith@whatever.com'
   '3'             'janed@thisthat.com'
   '4'             'peterg@notanemail.com'

What I am trying to come up with first namelast name and email for everyone that matches a certain district which is attribut_id = '336'. What I am trying is this:
SELECT CE.email as email,
    max(case when CEV.attribute_id = '5' then CEV.value end) as FirstName,
    max(case when CEV.attribute_id = '7' then CEV.value end) as LastName
FROM customer_entity_varchar CEV
LEFT JOIN customer_entity CE
ON ( CE.entity_id = CEV.entity_id)
WHERE CEV.value ='ADELANTO'
AND CEV.attribute_id='336'

My hopes for a result are:
           email                    FirstName             LastName

    jsmith@whatever.com               John                  Smith
    janed@thisthat.com                Jane                  Doe

However what I am getting back is a SINGLE row -- where email has a value, however both FirstName and LastName are blank. Is my logic flawed?

I would probably solve this like this. It's a solution that favours readability.
WITH firstNames AS
(SELECT entity_id, Value FROM customer_entity_char WHERE attribute_id = '5')
lastNames AS
(SELECT entity_id, Value FROM customer_entity_char WHERE attribute_id = '7')
districts AS
(SELECT entity_id, Value FROM customer_entity_char WHERE attribute_id = '336')
SELECT ce.email, fn.Value, ln.Value, d.Value FROM firstNames fn,lastNames ln, districts d
INNER JOIN customer_entity ce
WHERE fn.entity_id = ln.entity_id AND ln.entity_id = d.entity_id AND ce.entity_id = d.entity_id
AND d.Value = 'ADELANTO';

0 comments:

Post a Comment