UNION生成重复的行

时间:2013-11-12 08:07:02

标签: mysql sorting group-by sql-order-by union

我知道默认情况下UNION不会生成重复的行。但在这种情况下,因为我使用列sort_col进行排序,因此UNION生成重复行(实际上不重复,因为sort_col在每个select中都是不同的。要澄清,请看这个答案和comments 如何克服这个?

$key_word_1 = $what;    
$key_word_2 = $what."%";    
$key_word_3 = "%".$what."%";


(SELECT 1 AS sort_col, 
        chair.id_user, 
        chair.company, 
        chair.district, 
        chair.summary, 
        chair.place, 
        products.name 
 FROM   chair 
        LEFT JOIN products 
               ON chair.id_user = products.id_user 
 WHERE  ( chair.district LIKE ? 
          AND chair.place LIKE ? ) 
        AND ( chair.company LIKE ? 
               OR chair.summary LIKE ? 
               OR products.name LIKE ? 
               OR products.description LIKE ? ) 
 GROUP  BY chair.id_user) 
UNION 
(SELECT 2, 
        chair.id_user, 
        chair.company, 
        chair.district, 
        chair.summary, 
        chair.place, 
        products.name 
 FROM   chair 
        LEFT JOIN products 
               ON chair.id_user = products.id_user 
 WHERE  ( chair.district LIKE ? 
          AND chair.place LIKE ? ) 
        AND ( chair.company LIKE ? 
               OR chair.summary LIKE ? 
               OR products.name LIKE ? 
               OR products.description LIKE ? ) 
 GROUP  BY chair.id_user) 
UNION 
(SELECT 3, 
        chair.id_user, 
        chair.company, 
        chair.district, 
        chair.summary, 
        chair.place, 
        products.name 
 FROM   chair 
        LEFT JOIN products 
               ON chair.id_user = products.id_user 
 WHERE  ( chair.district LIKE ? 
          AND chair.place LIKE ? ) 
        AND ( chair.company LIKE ? 
               OR chair.summary LIKE ? 
               OR products.name LIKE ? 
               OR products.description LIKE ? ) 
 GROUP  BY chair.id_user) 
ORDER  BY sort_col 
LIMIT 
?, ? 

2 个答案:

答案 0 :(得分:1)

只需删除sort_col,因为实际联合将与订单连接(第二个选择结果将附加到第一个选择结果,第三个选择结果将在第二个选择结果之后)

答案 1 :(得分:0)

那不是重复的行。这是排序列的不同行原因。您可以通过排序列之外的所有列对这些分组进行查询。像这样:

SELECT MIN(sort_col) as sort, id_user, company, district, summary, place, name
FROM
(your query here)
GROUP BY id_user, company, district, summary, place, name
ORDER BY MIN(sort_col)