在联合查询后选择唯一行

时间:2015-04-01 15:46:37

标签: mysql mysqli

有这个查询:

(select status, cb_ebook, product_id, titel, auther, image from oc_product where status and cb_ebook and titel like '%term%') 
UNION               
(select status, cb_ebook, product_id, titel, auther, image from oc_product where status and cb_ebook and auther like '%term%')

但是,结果中有重复的行,我只想要唯一的product_id - 我尝试按product_id分组,但这不起作用。

任何解决方案?

3 个答案:

答案 0 :(得分:0)

您可以尝试在联合查询后添加distinct,例如?

SELECT distinct(x.status) status,x.cb_ebook,x.product_id,x.titel,x.auther,x.image
FROM
(
(select status, cb_ebook, product_id, titel, auther, image from oc_product where status and cb_ebook and titel like '%term%')
UNION
(select status, cb_ebook, product_id, titel, auther, image from oc_product where status and cb_ebook and auther like '%term%')
) x

答案 1 :(得分:0)

您不需要两个查询。只需将所有内容放入where子句

即可
select status, cb_ebook, product_id, titel, auther, image 
from oc_product 
where status 
and cb_ebook 
and (auther like '%term%' or titel like '%term%')

答案 2 :(得分:0)

Ues

UNION DISTINCT

而不是

UNION

你可以试试这个

(select status, cb_ebook, product_id, titel, auther, image from oc_product where status and cb_ebook and titel like '%term%') 
UNION DISTINCT              
(select status, cb_ebook, product_id, titel, auther, image from oc_product where status and cb_ebook and auther like '%term%')