Note that there are some explanatory texts on larger screens.

plurals
  1. POZF Sub Query Question
    primarykey
    data
    text
    <p>I've got a user table with user_id as the primary key and a user_dates table which has user_date_id as the primary key, user_id which links to the user table and start_date and end_date fields. </p> <p>I am trying to run a query to get a list of users and order them by the earliest date but only using the dates which haven't yet passed. Therefore, I am trying to run a sub query to get this date and then use it to order the users. </p> <p>So far I have got the following to link the tables but im not sure how to add a sub query in ZF?</p> <pre><code>$oSelect = $this-&gt;getDbConnection() -&gt;select() -&gt;from(array('u' =&gt; 'users'), '*') -&gt;joinInner(array('d' =&gt; 'user_dates') , 'u.user_id = d.user_id', array('start_date', 'end_date')) </code></pre> <p>The sub query is going to be something like:</p> <pre><code>SELECT start_date FROM user_dates d WHERE d.user_id=u.user_id &amp;&amp; start_date &gt; NOW() ORDER BY start_date ASC LIMIT 0,1 </code></pre> <p>Thanks</p> <p>So I could do the following:</p> <pre><code>$oSelect = $this-&gt;getDbConnection() -&gt;select() -&gt;from(array('u' =&gt; 'users'), '*') -&gt;joinInner(array('d' =&gt; 'user_dates') , 'u.user_id = d.user_id', array('start_date' =&gt; new Zend_Db_Expr('SELECT start_date FROM user_dates d WHERE d.user_id=u.user_id &amp;&amp; start_date &gt; NOW() ORDER BY start_date ASC LIMIT 0,1'), 'end_date;')) </code></pre> <p>I can't echo $oSelect because I havent got ZF on this machine but the query I am hoping to achieve is the following:</p> <pre><code>SELECT u . * , ( SELECT start_date FROM dates d WHERE d.user_id = u.user_id &amp;&amp; end_date &gt; NOW( ) ORDER BY start_date ASC LIMIT 0 , 1 ) AS date FROM `users` u INNER JOIN dates d ON u.user_id = d.user_id WHERE end_date &gt; NOW() GROUP BY u.user_id ORDER BY date ASC LIMIT 0 , 30 </code></pre> <p>You're right, ignore the above, the query should be:</p> <pre><code>SELECT u. * , ( SELECT start_date FROM dates d WHERE d.user_id = u.user_id &amp;&amp; end_date &gt; NOW( ) ORDER BY start_date ASC LIMIT 0 , 1 ) AS date FROM `users` u GROUP BY u.user_id HAVING date ORDER BY date ASC LIMIT 0 , 30 </code></pre>
    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