Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do you perform an AND with a join?
    primarykey
    data
    text
    <p>I have the following data structure and data:</p> <pre><code>CREATE TABLE `parent` ( `id` int(11) NOT NULL auto_increment, `name` varchar(10) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; INSERT INTO `parent` VALUES(1, 'parent 1'); INSERT INTO `parent` VALUES(2, 'parent 2'); CREATE TABLE `other` ( `id` int(11) NOT NULL auto_increment, `name` varchar(10) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; INSERT INTO `other` VALUES(1, 'other 1'); INSERT INTO `other` VALUES(2, 'other 2'); CREATE TABLE `relationship` ( `id` int(11) NOT NULL auto_increment, `parent_id` int(11) NOT NULL, `other_id` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; INSERT INTO `relationship` VALUES(1, 1, 1); INSERT INTO `relationship` VALUES(2, 1, 2); INSERT INTO `relationship` VALUES(3, 2, 1); </code></pre> <p>I want to find the the parent records with both other's 1 &amp; 2.</p> <p>This is what I've figured out, but I'm wondering if there is a better way:</p> <pre><code>SELECT p.id, p.name FROM parent AS p LEFT JOIN relationship AS r1 ON (r1.parent_id = p.id) LEFT JOIN relationship AS r2 ON (r2.parent_id = p.id) WHERE r1.other_id = 1 AND r2.other_id = 2; </code></pre> <p>The result is 1, "parent 1" which is correct. The problem is that once you get a list of 5+ joins, it gets messy and as the relationship table grows, it gets slow.</p> <p>Is there a better way?</p> <p>I'm using MySQL and PHP, but this is probably pretty generic.</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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