0

This is a part of my DB structure that I want to query:

DB structure

The relations are these:

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

I want to select the articles that are written from selected users (by usr_id) OR the article that have the selected tags (by tag_id) in one query if possible.

I have tried this but does not give me the desired result:

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 Answer 1

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>))

I wrote all joints so you can select all columns you want, but it can be done more rapidly if you just need article data :

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>))
Sign up to request clarification or add additional context in comments.

4 Comments

Thank but it's not working! Even if I use SELECT DISTINCT gives me an article twice..
Yes that's what's happening. Thank again for your time!
What can I do to get an article that has more than one tags linked to it, only one time?
You'll have to avoid displaying fields from tags or tags_article table, or using GROUP_CONCAT and GROUP BY commands.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.