加入两个表并从第二个表中读取两个记录

时间:2016-10-29 06:46:21

标签: mysql sql

我想加入两张桌子,从第一张桌子读取一张记录,从第二张桌子读取两张记录。第一个表有一些我想要选择的字段。第二个表已使用外键连接到第一个表。

第一张表格:

+----+-------------+
| id | some_fields |
+----+-------------+
| 23 |    S.T      |
+----+-------------+
| 24 |    S.T      |
+----+-------------+
| 25 |    S.T      |
+----+-------------+

第二张表

+----+----------+------------+
| fid| meta_key | meta_value |
+----+----------+------------+
| 24 |   meta_1 |   m_1      |
+----+----------+------------+
| 24 |   meta_2 |   m_2      |
+----+----------+------------+
| 25 |   meta_2 |   m_3      |
+----+----------+------------+

我想要的外线:

+----+-------------+--------+-------+
| id | some_fields | meta_1 | meta_2|
+----+-------------+--------+-------+
| 24 |     S.T     |   m_1  |  m_2  |
+----+-------------+--------+-------+
| 25 |     S.T     |   null |  m_3  |
+----+-------------+--------+-------+

我知道这个查询错了:

 SELECT *
    FROM posts
    INNER JOIN postmeta ON ( posts.id = postmeta.fid )
    WHERE 1 =1
    AND (
    postmeta.meta_key = 'meta_1'
    OR postmeta.meta_key = 'meta_2'
    )
    AND posts.post_type = 'ignition_product'
    AND (
    posts.post_status = 'publish'
    OR posts.post_status = 'private'
    )
    GROUP BY posts.ID
    ORDER BY postmeta.meta_value +0 DESC
    LIMIT 0 , 7

2 个答案:

答案 0 :(得分:3)

postmeta表使用多个联接:

SELECT posts.id, posts.some_fields, meta1.meta_value as meta_1, meta2.meta_value as meta_2
FROM posts
    LEFT JOIN postmeta meta1 ON posts.id = meta1.fid AND meta_key = 'meta1'
    LEFT JOIN postmeta meta2 ON posts.id = meta2.fid AND meta_key = 'meta2'
WHERE meta1.fid IS NOT NULL OR meta2.fid IS NOT NULL

首先JOIN将用于填充列meta_1的数据,第二个连接 - 填充列meta_2

如果您只有两种类型的元,则上述查询有效。如果您有更多或数字是动态的,则需要采用不同的方法。

答案 1 :(得分:3)

使用透视查询:

SELECT t1.id,
       t1.some_fields,
       t2.meta_1,
       t2.meta_2      
FROM posts t1
LEFT JOIN
(
    SELECT fid,
           MAX(CASE WHEN meta_key = 'meta_1' THEN meta_value END) AS meta_1,
           MAX(CASE WHEN meta_key = 'meta_2' THEN meta_value END) AS meta_2
    FROM postmeta
    GROUP BY fid
) t2
    ON t1.id = t2.fid