perkes456 perkes456 - 5 months ago 10
PHP Question

Returning a single record from many to many table

I have a table structure like following:

Users => Histories <= Brands

Histories table keeps following columns: userId, brandId, points

I have a query like following:

select b.id, sum(h.points),h.brandId
from brands b left join
histories h
on b.id = h.brandid and h.userId = 2866
group by b.id;


This query returns me brands where USER made points and didnt make any points at all..

I wanna add a filter to a brandId as well so that the query doesn't returns all results, but a single result at a time depending what brandId has been sent to the query... How can I and where can I add a statement which would return me a single record for this query?? So basically I just need to pass brandId = to something statement, leaving the query it self as it is right now ... :)

Answer

For example if brand id is 100:

select b.id, sum(h.points),h.brandId
from brands b left join
     histories h
     on b.id = h.brandid and h.userId = 2866
where b.id=100
group by b.id
limit 1;
Comments