Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If I understand it correctly, you want to remove the <code>rid</code> column from your <code>tag_rel</code> table, and have an automatically genarated position field in your query instead. The "position" of a tag in your case can be understood as the number of entries in the <code>tag_rel</code> table that have been added for a specific <code>pid</code>. In other words: all entries in the table with the same <code>pid</code> and an <code>id</code> that is equal or lower, assuming <code>id</code> is an autoincrement field.</p> <p>I think this can be done as follows. Mind you, it may not be the most efficient code in the world:</p> <pre><code>SELECT id, pid, tid, ( SELECT count(*) from tags_rel t2 where t2.pid = t1.pid and t2.id &lt;= t1.id ) AS rid FROM tags_rel t1; </code></pre> <p>I'm not entirely sure this will work, as I only have mysql 3 here, which doesn't do subqueries like this. I think it will though.</p> <p>If you may have more than 4 tags linked to a person, but you want only the first 4 tags for each person, you can now use:</p> <pre><code>SELECT * FROM ( [the above query] ) WHERE rid &lt;= 4; </code></pre> <p>This having been said, I think in almost all situations you might as well just <code>order by pid, id</code> and then adding the rank numbers in your output medium. But then, I don't know your situation.</p> <p>I think the most important thing is: is this what you meant? If so, hopefully some people on here will be able to provide you with the best answer to your question.</p> <p>EDIT:</p> <p>For your current query, this would amount to:</p> <pre><code>SELECT p.id as pid, t.tag as tname, tr.tid as trid, ( SELECT count(*) FROM tags_rel AS tr2 WHERE tr2.pid = tr.pid and tr2.id &lt;= tr.id ) AS rank FROM tags_rel AS tr LEFT JOIN people AS p ON tr.pid = p.id LEFT JOIN tags AS t ON tr.tid = t.id </code></pre> <p>assuming you don't need the <code>where rid &lt;= 4</code> part. (By the way: the <code>tr.tid as trid</code> kind of suggests you want to select <code>tags_rel.id</code> instead of the <code>tags_rel.tid</code> (== <code>tags.id</code>). I'm not sure if that's what you mean; if not, it might be better to select <code>tr.tid as tid</code> (or just <code>tr.tid</code>).)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload