Mysql
 sql >> Base de données >  >> RDS >> Mysql

Requête de sélection MYSQL en utilisant le nombre (*)

Maintenant que vous avez précisé ce que vous voulez réellement réaliser, on peut voir que le problème est beaucoup plus complexe. Vous voulez en fait toutes les combinaisons de subscriber_id et tag_id , puis comptez le nombre d'entrées réelles dans le produit de table jointe. ouf. Voici donc le SQL :

SELECT combinations.tag_id,
       combinations.subscriber_id,

-- correlated subquery to count the actual hits by tag/subscriber when joining
-- the two tables using content_id

       (SELECT count(*)
        FROM content_hits AS h
        JOIN content_tag AS t ON h.content_id = t.content_id
        WHERE h.subscriber_id = combinations.subscriber_id
        AND t.tag_id = combinations.tag_id) as cnt

-- Create all combinations of tag/subscribers first, before counting anything
-- This will be necessary to have "zero-counts" for any combination of
-- tag/subscriber

FROM (
  SELECT DISTINCT tag_id, subscriber_id
  FROM content_tag
  CROSS JOIN content_hits
) AS combinations