mysql 用于显示与多列匹配的行或基于城市-国家匹配将多行联接在一起的SQL查询

new9mtju  于 2023-02-28  发布在  Mysql
关注(0)|答案(4)|浏览(125)

我有一个类似这样的表:

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

我需要显示所有匹配国家〉城市的条目。或者按国家排序所有_aciudad条目;比如:

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

我不知道该怎么做我猜有一个内部连接?

jc3wubiy

jc3wubiy1#

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
7gs2gvoe

7gs2gvoe2#

我不确定这是否是您要查找的内容,或者JOIN ON字段是否正确,因为您的问题中它不是很清楚,但是这个查询怎么样?

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
xe55xuns

xe55xuns3#

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
zwghvu4y

zwghvu4y4#

尝试使用自联接。要使其工作,您必须为表使用别名,以便可以引用它两次。
大概是这样的

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"

相关问题