doctrine - SQL How do i query a many to many relationship -


If there are many relationships between my posts and tags, how do I choose posts with a special tag?

Update:

The problem I have is that where tag.name = 'xxx' , only that tag is selected. All I want is to select all the posts, whose tags are specified, TGT with all their tags, like

  1 post - & gt; Tag 1, Tag2 post 2 - & gt; Tag 1, tag3 post 3 - & gt; Tag 2, Tag 3  

What do I currently get

  post 1 - & gt; Tag 2 // missing tag 1 post3 - & gt; TagSag Tag 3  

Believing these tables:

    <
  • Post Tag: ID, name
  • Post tag: post_id, tag_ id

The last table is usually < Em> job table and facilitates many-to-many relationships between posts and tags.

  SELECT p = Pt.post_id pt.tag_id = t.id add tags. Name = 'SQL'  

In fact, think of multiple relationships as two-to-one relationships-no relationships, because they are commonly implemented in normal RDBMS gone. The above query breaks the post from the post-tag and includes one-to-many in the post tag from the second tag.

The post tag created by me is the overall primary key , code> (post_id, tag_id) this combination will be unique, defame the composite keys in many ways so that you Often people can create a primary key column:

  • PostTag: ID, Post_ID, TAG_ID

Any method is OK. This is largely a philosophical difference.

Update: If you want to select all the posts with a specific tag and tag all those tags then:

  SELECT p . * Add tags to JOIN posttags pt ON p.id = pt.post_id pt.tag_id = t.id 

tag_ id = t.id WHERE t.name = 'xyz')

Another way to do this is:

  SELECT p. Post tags, add tags on PT ptag.ag_id = t.id from PTTost.pdf.pt_post_id pt.tag_id = t.id, where the existing (SELECT post_id) PostTag pot is added to PT ptag.ag_id = t.id, where t.name = 'xi 'And PT .post_id = p.id)  

which performs better, will need to be checked and databases may vary by vendor and version. A good optimizer (i.e. Oracle) will probably optimize them to perform the same. Other can not be.

You will now get back rows like this:

  1 post, 1 post1, tag2 post3, tag2 post3, tag3  

So you will need to combine them, preferably in application logic instead of SQL Some RDBMSs are vendor-specific extensions for this type of object, such as MySQL function.


Comments

Popular posts from this blog

Eclipse CDT variable colors in editor -

AJAX doesn't send POST query -

wpf - Custom Message Box Advice -