How do i ensure no duplicates with this query
I have this query
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)
and the rows being returned have duplicate product_id
. For example:-
som开发者_如何转开发ething product_id model
NULL 20 18924
barcode_labels 20 18924
NULL 21 18926
barcode_labels 21 18926
NULL 22 30332
barcode_labels 22 30332
I tried DISTINCT
on the product_id
and I also tried in the WHERE
clause "and something is not null" and both failed. Is there a solution to this?
You might want something like this (I also refactored the code a bit). However, if you have more than just barcode_labels
as a keyword, you'll still get an additional entry for each other combination.
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)
Another way would be to play around with the group by
clause to get what you want. Try something like this:
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
You can group the records:
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
but you don't have alot of control over which information is displayed after the grouping. In your case, in the something column, should it show NULL
or barcode_labels
?
精彩评论