def find_related_tags(tags, options = {})
tag_names = ActiveRecord::Acts::Taggable.split_tag_names(tags, options[:separator], normalizer)
o, o_pk, o_fk, t, tn, t_pk, t_fk, jt = set_locals_for_sql
options[:limit] += 1 if options[:limit]
sql = "SELECT jt.#{o_fk} AS o_id FROM #{jt} jt, #{t} t
WHERE jt.#{t_fk} = t.#{t_pk} "
sql << " AND ( t.#{tn} IN ("
sql << quote_bound_value(tag_names)
sql << "))"
sql << "GROUP BY jt.#{o_fk}
HAVING COUNT(jt.#{o_fk})=#{tag_names.length}"
o_ids = connection.select_all(sql).map { |row| row['o_id'] }
return options[:raw] ? [] : {} if o_ids.length < 1
sql = "SELECT t.#{t_pk} AS id, t.#{tn} AS #{tn}, COUNT(jt.#{o_fk}) AS count FROM #{jt} jt, #{t} t
WHERE jt.#{o_fk} IN (#{o_ids.join(",")})
AND t.#{t_pk} = jt.#{t_fk}
GROUP BY t.#{t_pk},t.#{tn},jt.#{t_fk}
ORDER BY count DESC"
add_limit!(sql, options)
result = connection.select_all(sql).delete_if { |row| tag_names.include?(row["#{tn}"]) }
count = result.inject({}) { |hsh, row| hsh[row["#{tn}"]] = row['count'].to_i; hsh } unless options[:raw]
count || result
end