Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

As I'm working my way through Celkos "SQL for Smarties", he points out an interesting way to map such boolean queries by using GROUP BY and HAVING:

-- find all book ids coauthored by Smith and Jones: -- (let's assume that the author_name is unique) select book_id, count(*) from authors where author_name = 'Smith' or author_name = 'Jones' group by book_id having count(*) = 2

Whether the performance of this is better or worse than selecting all books by one and all books by the other and scanning the lists in Perl, or worse than dynamically creating the self joins needs to be benchmarked. Another way to make this slightly less dynamic could be to use the IN predicate:

-- find all book ids coauthored by Smith and Jones: -- (let's assume that the author_name is unique) select book_id, count(*) from authors where author_name in ('Smith', 'Jones') group by book_id having count(*) = 2

To make it completely static, you could insert the authors into a (session-local) temporary table and cross-join that table.

Update: Oops - this approach will also return books co-authored by 'Smith', 'Jones' and 'Miller'. Depending on whether that's what you want or not, you will need to use a subselect to make sure you get all of the authors. But I'm not sure if I can come up with the correct subselect at the moment :-)


In reply to Re: Many-to-many relationships in databases by Corion
in thread Many-to-many relationships in databases : SOLVED by CountZero

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (4)
As of 2024-04-25 13:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found