Note that there are some explanatory texts on larger screens.

plurals
  1. POCounting records of a table with multiple foreign keys (MySQL)
    primarykey
    data
    text
    <p>I have a MySQL database with various tables whose records can be tagged, so I have a <code>tags</code> table, and a <code>tag_associations</code> table that relates tags to other "taggable" tables via multiple foreign keys, and also to an "owning" user -- my fields are something like the following:</p> <ul> <li>tag_association_id (primary key)</li> <li>user_id (tag association creator)</li> <li>tag_id (related tag)</li> <li>artist_id (tagged artist, can be null)</li> <li>album_id (tagged album, can be null)</li> <li>track_id (tagged track, can be null)</li> </ul> <p>I basically want to count all items that have been tagged a particular tag -- so something along the results of this query:</p> <pre><code>SELECT COUNT(ta.tag_association_id) AS how_many FROM tag_associations AS ta LEFT JOIN users AS u ON ta.user_id = u.user_id WHERE ta.tag_id = '480' AND u.user_status = 'active' </code></pre> <p>But the problem with this query lies in cases where the same tag has been applied to the same item by multiple users, so if 2 different users tag the artist 'Bobby Jones Band' as 'rad', it counts both of the tag associations where I just want to count it once. I tried adding this to the above:</p> <pre><code>GROUP BY ta.artist_id, ta.album_id, ta.track_id </code></pre> <p>...which got me close, but didn't yield the exact results I needed -- it gave me multiple row results of different counts. Is there any magic I can use in a case like this and keep it in a single query? While remaining as efficient as possible, of course :) Thanks!</p>
    singulars
    1. This table or related slice is empty.
    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. 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