Note that there are some explanatory texts on larger screens.

plurals
  1. POQuery with sub-results from another table
    primarykey
    data
    text
    <p>I have the following two database tables:</p> <pre><code>`membership_members` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` tinytext NOT NULL, `active` tinyint(1) NOT NULL DEFAULT '1', PRIMARY KEY (`id`) ) `membership_payments` ( `date` date NOT NULL, `amount` int(11) NOT NULL, `member` int(11) NOT NULL, KEY `member` (`member`) ) </code></pre> <p>I wish to list all the members, and for each of them I would like to show the list of all the payments by that member. The <code>membership_payments.member</code> column is a foreign key <code>membership_members.id</code> (this is MySQL so I cannot explicitly specify a foreign key). Notice that I do want to list a member even if he doesn't have any payments.</p> <p>So something like:</p> <pre><code>* John Smith - 2012-05-06 $100 - 2012-01-02 $100 * Brian Jones * Mike Jackson - 2012-09-02 $50 </code></pre> <p>I have tried with this query:</p> <pre><code>SELECT id, name, active, date, amount FROM `membership_members`, `membership_payments` WHERE membership_members.id = member </code></pre> <p>This of course gives me tha data I need, but not exactly how I need it as it returns a row for each payment. That means that I later have to group the rows (in PHP) by member id so that I don't list a member multiple times. I <em>can</em> do that, but I believe that it would be easier and faster to do it in SQL. Also, this query only gives me users which have payments with their id.</p> <p>I feel that this should be simple, but last time I did anything but the most simple stuff in SQL was 6-7 years ago.</p> <p><strong>EDIT:</strong> <code>LEFT OUTER JOIN</code> suggested in one of the answers solves the issue with the "missing" members. But what is the best way of grouping results by member IDs? I know there is a <code>GROUP BY</code> clause, but it doesn't give me all the payments for the given member, only one. I suppose I can run a new payments query for each member, but I fear this would be very inefficient (we have around 300-400 members).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload