SQL - How Can I Order By Count From Other Table -


hey stackoverflow community,

i know question asked before, don't understand answerts cant use own project. amazing if me please.

i'm creating little private url shortener , want order urls views count. setup database like

  • table: urls: id, user_id, alias, url, title, created
  • table: views: id, user_id, alias, visitor_ip, created

if clicks short link ask stored date (user_id) url , add row views user_id , alias know link clicked , user has created url. how can urls order rows in views same alias?

something correct syntax

select * urls user_id = {anyuser} order count(alias) views 

thanks reading , hope can me. :)

edit because of questions in comments.

sorry missunderstanding. have 3 tables users, urls, views. if registers gets auto incrementing user_id. if user creates short url adds row urls (user_id, alias, title) alias random generated string example: example.com/ dhejk if somone visits url first ask user_id belongs alias (dhejk) , store in variable after add row views data (user_id, alias) user_id = {the stored user} , alias = dhejk. want list urls in users dashboard orderd viewed. mosted views gets defined how rows in table views alias dhejk

you can join query against view table.

select u.*, v.view_count urls u  left outter join  (select user_id, count(*) view_count views group user_id) v on u.user_id = v.user_id u.user_id = {anyuser} , u.alias = {anyalias} order v.view_count 

i think part of problem table/relationship design. tables related alias(derived original query) , user_id. provided alias , user_id same in both tables, make more sense establish pk/fk relationship shown below whereas urls primary key foreign key in teh views table. enter image description here