Note that there are some explanatory texts on larger screens.

plurals
  1. POTrying to simplify a MySQL query
    primarykey
    data
    text
    <p>I would really appreciate any help trying to simplify a MySQL query. The purpose of the query is to retrieve messages from a messages table (users_messages) which has the following columns: message_id, from_id, to_id, message_content, date_sent.</p> <p>The from_id and to_id need to join a users table (users) which has these columns: user_id, user_username.</p> <p>Also I should mention that there is a blocked users table (users_blocked) which filters out any messages should the user_id feature in this table.</p> <p>All this works fine and messages are ordered with the newest first which is what I want. My only problem is that it's not pulling the corresponding 'message_content'. i.e. it's pulling the most recent date, but not the most recent message.</p> <p>Perhaps I need a different approach (e.g. subqueries) but I can not get my head around it.</p> <p>Here is the query:</p> <pre><code>select m.message_content, if(from_id &lt; to_id, concat(from_id,to_id), concat(to_id,from_id)) as ft, if (from_id = $my_id, to_id, from_id) as other_id, max(date_sent) as most_recent from users_messages m left join users_blocked ub1 on (from_id = ub1.blocked_id and ub1.user_id = $my_id) left join users_blocked ub2 on (to_id = ub2.blocked_id and ub2.user_id = $my_id) where (from_id = $my_id or to_id = $my_id) and ub1.blocked_id is null and ub2.blocked_id is null group by ft order by most_recent desc </code></pre> <p>Sorry, here are the table structures:</p> <p>users</p> <pre>user_id user_username 1 Simon 2 Amber 3 Tom</pre> <p>users_messages</p> <pre> message_id from_id to_id date_sent message_content 1 1 2 2012-07-04 11:52:12 Hello 2 1 2 2012-07-04 12:32:24 Another message 3 1 2 2012-07-04 14:00:00 Hello again </pre> <p>users_blocked</p> <pre> user_id blocked_id 1 3 </pre>
    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