我有这个查询
SELECT
(SELECT keyword FROM url_aliAS WHERE query = CONCAT("category_id" , '=', p2c.category_id)) AS something,
p.product_id, p.model FROM product AS p
JOIN product_to_category p2c ON (p.product_id = p2c.product_id)
WHERE p.product_id NOT IN (280, 129, 131)
并且返回的行具有重复的product_id
。例如: -
something product_id model
NULL 20 18924
barcode_labels 20 18924
NULL 21 18926
barcode_labels 21 18926
NULL 22 30332
barcode_labels 22 30332
我在DISTINCT
上尝试了product_id
,我也尝试了WHERE
子句“并且某些内容不为空”并且都失败了。有解决方案吗?
答案 0 :(得分:2)
你可能想要这样的东西(我也稍微重构了一下代码)。但是,如果您的关键字不仅仅是barcode_labels
,那么您仍会为其他组合获得额外的条目。
select
u.keyword as something,
product_id,
p.model
from
product p
join product_to_category p2c using (product_id)
join url_alias u on (u.query = concat("category_id=", p2c.category_id))
where
u.keyword is not null
and p.product_id not in (280, 129, 131)
另一种方法是使用group by
子句来获得你想要的东西。尝试这样的事情:
select
max(u.keyword) as something,
product_id,
p.model
from
product p
join product_to_category p2c using (product_id)
join url_alias u on (u.query = concat("category_id=", p2c.category_id))
where
u.keyword is not null
and p.product_id not in (280, 129, 131)
group by
product_id,
p.model
答案 1 :(得分:0)
您可以对记录进行分组:
SELECT
(SELECT keyword FROM url_aliAS WHERE query = CONCAT("category_id" , '=', p2c.category_id)) AS something,
p.product_id, p.model FROM product AS p
JOIN product_to_category p2c ON (p.product_id = p2c.product_id)
WHERE p.product_id NOT IN (280, 129, 131)
GROUP BY p.product_id
但您对分组后显示的信息没有很多控制权。在您的情况下,在某个列中,它应显示NULL
还是barcode_labels
?