Question

I have a table that looks like this:

meta_id post_id     meta_key    meta_value
271     4   _aciudad             New york
270     4   _apais               USA
267     10  _aservicio           Alojamiento

...
261     43  _apais               USA
238     43  _aciudad             Chicago
262     43  _aservicio           Alojamiento
...
261     43  _apais               USA
238     43  _aciudad             Miami
262     43  _aservicio           Alojamiento

What i need to do, is to display all the registers that matches Country > City. Or order all the _aciudad registers by country, something like:

meta_id post_id  meta_key   meta_value       meta_key    meta_value 
235      42      _aciudad        New York     _apais       USA
236      56      _aciudad        Chicago      _apais       USA
237      57      _aciudad        Miami        _apais       USA
238      58      _aciudad        Sidney       _apais      Australia
238      59      _aciudad        Melbourne    _apais      Australia

I have no idea how to do this, i guess with a INNER JOIN? a double select? Please help me!!

Was it helpful?

Solution

   SELECT t1.meta_id, 
           t1.post_id, 
           t1.meta_key, 
           t1.meta_value, 
           t2.meta_key, 
           t2.meta_value 
    FROM table t1, table t2  
    WHERE t1.post_id = t2.post_id 
    AND t1.meta_key = '_apais'
    AND t2.meta_key = '_aciudad'
    ORDER BY t1.meta_key

OTHER TIPS

I'm not sure if this is what you're looking for, or if the JOIN ON field is correct because it's not very clear in your question but what about this query?

SELECT City.meta_id
     , City.post_id
     , City.meta_key
     , City.meta_value
     , Country.meta_key
     , Country.meta_value
  FROM yourTable City
INNER JOIN yourTable Country ON City.post_id = Country.post_id
WHERE City.meta_key = '_aciudad' AND Country.meta_key = '_apais'
ORDER BY Country.meta_value, City.meta_value
SELECT  mc.*, mp.meta_key, mp.meta_value
FROM    meta mc
JOIN    meta mp
ON      mp.post_id = mc.post_id
        AND mp.meta_key = '_apais'
WHERE   mc.meta_key = '_aciudad'
ORDER BY
        mp.meta_value, mc.meta_value

Try a self-join. To make it work you have to use aliases for the table, so you can refer to it twice.

Something like this:

select

  t1.meta_id, t1.post_id,
  t1.meta_key, t1.meta_value, 
  t2.meta_key, t2.meta_value

from TableName t1
  inner join TableName t2
  on t1.meta_id = t2.meta_id and t1.post_id = t2.post_id
    and t1.meta_key = "_aciuidad" and t2.meta_key = "_apais"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top