首页 > 对多对,跨表查询,sql语句怎么写,急,在线等

对多对,跨表查询,sql语句怎么写,急,在线等

下面是数据库结构,Relationships是文章表和类别、标签表的关系表,他们是多对多。

我现在在aid=1的详情页面,查询相同相同类别的文章。 这个sql语句怎么写?

目前实现了想要的功能,感谢 @rockman

    $midSql = 'SELECT relationships.mid FROM relationships INNER JOIN metas ON metas.mid = relationships.mid WHERE relationships.aid = :aid AND metas.type =  "category"';

    $aidSql = 'select relationships.aid from relationships where relationships.aid != :aid AND relationships.mid IN ( '.$midSql.' )';

    $sql = 'select articles.aid,articles.title fromarticles where articles.aid IN ( '.$aidSql.' )';

可能你们能有更好的方案,可以一起探讨下。

Metas 类别、标签表
category是类别,tag是标签

Articles 文章表
aid、title、created、modified、text、viewNum
1   title1
2   title2
3   title3

Metas 类别、标签表
mid、name、count、parent、type 
1 、category1、0、0、category
2 、category1、3、1、category
3 、 tag1、  3 、0、tag 

Relationships 关系表
aid、mid
1、2
1、3
2、2
2、3
3、2
3、3

能否弄成两步来实现呢?

先获取该文章的类别,然后再搜索这几个类别下的文章列表(把当前文章排除掉)

SELECT r1.aid FROM Relationships r1 WHERE r1.aid!=1 AND r1.mid IN (SELECT r2.mid FROM Relationships r2 LEFT JOIN Metas m ON m.mid=r2.mid WHERE r2.aid=1 AND m.type='category')

【热门文章】
【热门文章】