如何加入这些表格?可能吗?

时间:2012-10-17 17:04:50

标签: mysql

表文章存储文章id蚂蚁标题值。类似的表通过匹配article =相似的表ID来添加具有similar_id的额外文章。

我最好显示输出,很难用文字解释:

Article with id 3 -> Title3 Text3
when
Similar articles -> Title1(voteup,votedown), Title2(voteup,votedown)

因为文章表id =类似的表id。 (3 = 3 [similar_id 1],3 [similar_id 2]。) 并且可能当文章输出类似的文章ID时,它必须返回并从第一个表中获取similar_id的标题。

-

Table Articles:

    ID     Title    text

    1      title1   text1
    2      title2   text2
    3      title3   text3

Table Similar:

    ID     Similar_ID   voteup votedown

    1          2          50      2
    2          3         1621    531
    3          1         ...     ...
    3          2         ...     ...

1 个答案:

答案 0 :(得分:1)

根据您的要求,Similar_ID字段在此处是红色鲱鱼,不应包含在查询中:

SELECT articles.Title, similar.VoteUp, similar.VoteDown
FROM articles
JOIN similar ON articles.ID = similar.ID
WHERE articles.ID = 3

要包含类似的标题(虽然我不太确定您希望如何构建数据),但您可以这样做:

SELECT articles.Title, similar.VoteUp, similar.VoteDown, similar_articles.Title AS SimilarTitle
FROM articles
JOIN similar ON articles.ID = similar.ID
JOIN articles similar_articles ON similar.Similar_ID = similar_articles.ID
WHERE articles.ID = 3