如何创建一个子查询而不是union

时间:2015-10-16 13:49:38

标签: mysql join optimization union-all

我有这样的查询,我觉得它可以更短,更恶化。有人有想法吗?

select * from table where match(col1) against('anything') and col2 in('10')
   union distinct
select * from table where match(col1) against('anything')

现在我想知道我可以使用sub-queryjoin实现上述查询吗?

编辑:我在现实中的查询:(专注于两个第一个select子句)

SELECT @rank := @rank + 3 `rank`, id, subject, name, matnF, source, 'quran' which 
  FROM quran, (select @rank := -2) q
     WHERE MATCH (`translate`, subject, name) AGAINST (:q) and aye IN (" .implode(',', $matches[0]) . ")

UNION DISTINCT

SELECT @rank1 := @rank1 + 3 `rank`, id, subject, name, matnF, source, 'quran' which 
  FROM quran, (select @rank1 := -1) q 
     WHERE MATCH (`translate`, subject, name) AGAINST (:q)

UNION ALL

SELECT @rank2 := @rank2 + 3 `rank`, id, subject, byA, matnF, source, '' `translate`, 'hadith' which 
  FROM hadith, (select @rank2 := 0) q 
     WHERE MATCH (subject) AGAINST (:q)

ORDER BY rank LIMIT :j, 11

我希望使用CASE WHEN ... THEN ...进行两次首次查询并将它们合并。

Edit2:这看起来像我想要的:

(SELECT @rank1 := @rank1 + 2 `rank`, id, subject, name, matnF, source, 'quran' which 
  FROM quran, (select @rank1 := -1) q 
     WHERE MATCH (`translate`, subject, name) AGAINST (:q)
        ORDER BY CASE 
            WHEN aye IN (" .implode(',', $matches[0]) . ") THEN 0
            ELSE 1
        END
)

    UNION ALL

(SELECT @rank2 := @rank2 + 2 `rank`, id, subject, byA, matnF, source, '' `translate`, 'hadith' which 
      FROM hadith, (select @rank2 := 0) q 
         WHERE MATCH (subject) AGAINST (:q)
)

ORDER BY rank LIMIT :j, 11

1 个答案:

答案 0 :(得分:2)

如果不需要重复项,下面的查询应该为您提供所需的输出

select a.* 
from table1 a 
where match(col1) against('anything')
ORDER BY 
 CASE
  WHEN col2 IN ('10') THEN 0
  ELSE 1
 END
;