多个AS语句的sql union重复问题

时间:2012-02-17 05:24:28

标签: php sql union

使用以下sql查询:

  SELECT id, title, description, publisher,
         city, state, date,
         MATCH (title, description, publisher) AGAINST ('pizza+view' IN BOOLEAN MODE) AS score 
    FROM job 
  HAVING score > 0.01 
  UNION 
  SELECT id, title, description, publisher,
         city, state, date, ( 3959 * acos( cos( radians('37') ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians('-122') ) + sin( radians('37') ) * sin( radians( latitude ) ) ) ) AS distance
    FROM job
  HAVING distance < '175'
ORDER BY distance DESC
   LIMIT 0, 30

结果回归:

id  title   description publisher   city    state   date    distance

得分作为距离发回,因此没有唯一的行。

我该如何更改?

2 个答案:

答案 0 :(得分:1)

我会使用子查询并按分数和距离字段对结果进行排序,因此具有相同分数的行将按距离排序。我从最终结果集中删除了得分列,我不确定在这种情况下你是否需要它。

select id, title, description, publisher, city, state, date from (
    SELECT 
        id, title, description, publisher, city, state, date,
        MATCH (title, description, publisher) AGAINST ('pizza+view' IN BOOLEAN MODE) AS score,
        (3959 * acos( cos( radians('37') ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians('-122') ) + sin( radians('37') ) * sin( radians( latitude ) ) ) ) AS distance
    FROM job 
) t
where score > 0.01 or distance < 175
order by score desc, distance desc
limit 0, 30

答案 1 :(得分:0)

尝试将CTE用于第一个语句。 像这样:

WITH score as (  SELECT id, title, description, publisher, 
     city, state, date, 
     MATCH (title, description, publisher) AGAINST ('pizza+view' IN BOOLEAN MODE) AS score  
FROM job  
HAVING score > 0.01 )

SELECT j.id, j.title, j.description, j.publisher, 
     j.city, j.state, j.date, ( 3959 * acos( cos( radians('37') ) * cos( radians( latitude ) )   
     *        cos( radians( longitude ) - radians('-122') ) + sin( radians('37') ) * sin(   
radians  ( latitude ) ) ) ) AS distance, s.score
FROM job j
LEFT OUTER JOIN score s ON s.ID = j.ID
HAVING j.distance < '175' 
ORDER BY distance DESC 
LIMIT 0, 30