It appears to me that your usertable looks something like this:
id username branches
1 vroom gods,QandA,janitors
2 merlyn janitors
3 Ovid power users,janitors
4 dws power users,janitors,pmdev
This is violating the First Normal Form, which roughly states that no field of a table
may contain multiple values. That's why we use Relational Databases in the first place,
so that we don't have to use an outside Programming Language to
split the values apart.
Instead, you make another table, called
branch or
branches:
id name
1 gods
2 QandA
3 janitors
4 power users
5 pmdev
Now, if a given user can only belong to one 'branch', then our user table might look like:
(2nd Normal Form)
id username branch_id
1 vroom 1
2 merlyn 3
3 Ovid 4
4 dws 4
If we need to pull out the branches, SQL to the rescue!
SELECT user.username, branch.name
FROM user
INNER JOIN branch ON user.branch_id = branch.id
However, a given user can belong to multiple branches, so we need employ the 3rd Normal Form.
Start by removing the branch_id column from the user table, then create a new table - a
3rd table that will join Users to Branches: (user_branches)
user_id branch_id
1 1
1 2
1 3 (vroom belongs to 1, 2, and 3)
-------------
2 3 (merlyn is a janitor)
-------------
3 4
3 3 (Ovid is power user and janitor)
-------------
4 4
4 3
4 5
The SQL to join all three tables together is trickier, but the more you practice,
the better you get. Here it is:
SELECT user.username, branch.name
FROM user
INNER JOIN user_branches ON user.id = user_branches.user_id
INNER JOIN branch ON user_branches.branch_id = branch.id
If you database tables are set up "properly", then you minimize the amount of work
you have to do youself in Perl. Let the database do that work for you. :)
-
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.