选择多个表格

时间:2012-11-22 20:21:35

标签: mysql sql join

这是我要查询的数据库结构的一部分:

DB structure

关系是这些:

  • article.art_author - user.usr_id
  • article.art_id - tag_article.rel_art_id
  • tag_article.rel_tag_id - tag.tag_id

如果可能的话,我想在一个查询中选择从所选用户(通过usr_id)编写的文章或具有所选标签的文章(通过tag_id)。

我试过这个,但没有给我预期的结果:

SELECT * FROM 
                ((article JOIN user on article.art_author = user.usr_id)
                JOIN
                tag_article on article.art_id = tag_article.rel_art_id)
                JOIN
                tag on tag_article.rel_tag_id = tag.tag_id
                WHERE
                article.art_lang = '$cur_lang'
                $sql_in
                ORDER BY
                article.art_date desc
                LIMIT $first_record, $range

1 个答案:

答案 0 :(得分:1)

select distinct a.art_id
from article a,
    user u,
    tag_article ta,
    tag t
where a.art_author=u.user_id
    and ta.rel_art_id = a.art_id
    and ta.rel_tag_id = t.tag_id
    and (u.usr_id in (<your selected users>) or t.tag_id in (<your selected tag>))

我编写了所有关节,因此您可以选择所需的所有列,但如果您只需要文章数据,则可以更快地完成:

select a.art_id
    from article a,
    tag_article ta
where a.art_id=ta.rel_art_id
    and (a.art_author in (<your selected users>) or ta.rel_tag_id in (<your selected tags>))