MySQL Forums
Forum List  »  Newbie

SQL: relations, LEFT JOIN with spec column
Posted by: prog
Date: April 04, 2005 08:57PM

Hi all!

I apologize for may be stuped question and for my bad English too.

_INTRO_:

I have two tables:
product: id, title ...
accessory: id, title ...

and relation table "many to many":
product_accessory (pid, aid)

I know how to recieve the list of accessories that belongs to selected product (productId). SQL is:

"SELECT a.id, a.title
FROM product_accessory as rel LEFT JOIN accessory as a ON (a.id=rel.aid)
WHERE (rel.pid='sony_DCR-HC_20E')"

And the list of all accessories is, clear:
SELECT a.id, a.title FROM accessory AS a [WHERE filter_expression]

_QUESTION_:

But what that I want is to recieve for selected product the list of all(!) accessories, but with specialized column by which i can determine if the accessory belongs to selected product.

I tested some SQLs:

"SELECT a.id, a.title, rel.aid FROM accessory AS a
LEFT JOIN product_accessory AS rel ON rel.aid=a.id
WHERE (rel.pid='sony_DCR-HC_20E') or (rel.aid IS NULL)
ORDER BY a.title"

But there are not accessories in obtained list that present in the relation table except of selected product.

Or

"SELECT a.id, a.title, rel.pid='sony_DCR-HC_20E' FROM accessory AS a
LEFT product_accessory AS rel ON rel.aid=a.idORDER BY a.id"

But in this case there are unnecessary rows of dubble accessory - with difirenced third column.
(The same result is if DISTINCT in last SQL is used.)


I feel that the truth is nearby, but I have ranked my brains over this question all night long.

Thanks for help.
Alex Gudchenko.

Options: ReplyQuote


Subject
Written By
Posted
SQL: relations, LEFT JOIN with spec column
April 04, 2005 08:57PM
April 05, 2005 01:33PM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.