fix #1536 by adding another subselect to create a temp table