0

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

$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 
?, ? 
4

2 回答 2

1

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

于 2013-11-12T08:51:46.803 回答
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)
于 2013-11-12T08:54:13.320 回答