views:

42

answers:

1

Hello

I have two tables. One is article and the other structure. And the articles can be viewed as a tree with childnodes and so on. Like the Windows forms control TreeView.

The structure table basically looks this:

  • article_id
  • article_above_id

Article:

  • article_id
  • article_number

I want to select from a maximum of five article_number's and from that show the article which has these articles under it in the tree.

The article_number-data comes from a GUI where at least one is required and will be null if nothing entered.

A: 

You can select the five articles and join in their parent articles, group on the parent articles and get only the articles that has five matches for child articles.

select p.article_id
from Article a
inner join Structure s on s.article_above_id = article_id
inner join Article p on p.article_id = s.article_id
where a.article_number in (3,7,45,186,203)
group by p.article_id
having count(*) = 5

(Note: I used the "above" field in the structure table to mean above in the tree, i.e. the id of the child item. If you have turned the tree upside down and have the leaves hanging under the root, you will have to switch the use of the fields.)

Guffa
This wouldn't account for the user only entering four article numbers, or? The articlenumbers a strings btw.
Erik
@Erik: Yes, you would have to change the content in the in() and the number to compare the count to. How to best do that depends of course on how you run the query. Using strings instead of numbers in the in() is not a problem.
Guffa
Thank you! Got it to work using a case on the count-value.
Erik