better SQL query for linked items