DISTINCT关键字在mysql查询中不起作用

时间:2016-01-10 09:38:38

标签: mysql join

我遇到了一个问题,我的mysql查询没有按预期工作。我使用union加入3个表格,从结果中我想忽略重复的单词。为此,我使用了DISTINCT个关键字。但它没有按预期工作。

我的查询是,

SELECT DISTINCT(catnam), sub2id 
FROM tbl_first_page_products f INNER JOIN subcategory_level2 s 
ON f.brand_id = s.sub2id 
WHERE f.title_cat = 'men' 
UNION 
SELECT DISTINCT(catnam), sub2id 
FROM tbl_third_page_products f INNER JOIN subcategory_level2 s 
ON f.brand_id = s.sub2id 
WHERE f.title_cat = 'men' 
UNION 
SELECT DISTINCT(catnam), sub2id 
FROM tbl_fourth_page_products f INNER JOIN subcategory_level2 s 
ON f.brand_id = s.sub2id 
WHERE f.title_cat = 'men'

我的结果是,

catnam    sub2id
------    ------
Levi's      4
United      1
Reebok     130
Jack       18
Proline    77
Levi's     161
Arrow      284

在上面的结果中Levi's正在重复。如何忽略这一点。我只需要一个Levi's。有没有办法避免这种情况。我被困在这里。

2 个答案:

答案 0 :(得分:2)

具有多列的MySQL DISTINCT

您可以将DISTINCT子句与多个列一起使用。在这种情况下,MySQL使用所有列的组合来确定结果集中行的唯一性。

http://www.mysqltutorial.org/mysql-distinct.aspx

如果你想解决你的问题,可以使用group_concat()函数,然后按照catnam对所有联合查询进行分组:

SELECT name ,GROUP_CONCAT(id)  
FROM your_table
GROUP BY name ; 

所以您的查询可以是:

SELECT distinct(catnam) as catnam, GROUP_CONCAT(sub2id )  
FROM tbl_first_page_products f INNER JOIN subcategory_level2 s 
ON f.brand_id = s.sub2id 
WHERE f.title_cat = 'men'
UNION 
SELECT distinct(catnam) as catnam, GROUP_CONCAT(sub2id )
FROM tbl_third_page_products f INNER JOIN subcategory_level2 s 
ON f.brand_id = s.sub2id 
WHERE f.title_cat = 'men' 
UNION 
SELECT distinct(catnam) as catnam, GROUP_CONCAT(sub2id ) 
FROM tbl_fourth_page_products f INNER JOIN subcategory_level2 s 
ON f.brand_id = s.sub2id 
WHERE f.title_cat = 'men'
group by catnam

答案 1 :(得分:2)

我试试:

SELECT n, GROUP_CONCAT(sub2id )
FROM
(
SELECT catnam n, sub2id 
...
UNION
SELECT catnam, sub2id
...
)
GROUP BY n