按ID选择第三个表

时间:2015-08-13 09:13:26

标签: php mysql join

Mysql详细信息:

  • 表A(姓名:职位):id
  • 表B(名称:post_has_relate):post_id,object_id

我可以使用相同的object_id获取表A中的帖子,post_id是const吗?我尝试用子查询编写。我能用join编写吗?

SELECT
    p.sumary AS sumary,
    p.source_link AS source_link,
    p.source_name AS source_name,
    p.created AS created,
    p.id AS id,
    p.slug AS slug
FROM
    post_has_relate AS pr
LEFT JOIN post as p ON p.id = pr.post_id
WHERE
    pr.object_id IN (
        SELECT
            post_has_relate.object_id AS object_id
        FROM
            post_has_relate
        WHERE
            post_has_relate.post_id = 1052
    )
AND pr.post_id != 1052
AND p. STATUS = 1
GROUP BY
    p.id
ORDER BY
    p.created DESC
LIMIT 5 OFFSET 0

1 个答案:

答案 0 :(得分:0)

我认为您可以通过加入获得相同的结果:

SELECT
    p.sumary AS sumary,
    p.source_link AS source_link,
    p.source_name AS source_name,
    p.created AS created,
    p.id AS id,
    p.slug AS slug
FROM
    post_has_relate AS pr
LEFT JOIN post as p ON p.id = pr.post_id
JOIN post_has_relate AS pr2 
    ON pr2.object_id=pr.object_id AND pr2.post_id=1052
WHERE
    pr.post_id != 1052
    AND p.STATUS = 1
GROUP BY
    p.id
ORDER BY
    p.created DESC
LIMIT 5 OFFSET 0