3

I've got one main users database table and a "meta" table to outer join. Basically the essential query is

SELECT * FROM users_table 
LEFT OUTER JOIN meta_table ON users_table.id = meta_table.user_id 
ORDER BY users_table.id ASC

But I have to limit results on the users_table ID column. If I use the standard LIMIT clause, the query will count also meta values.

Would be possible to limit on the user's table ID column and associate metas with the join?

2
  • What do you mean by the query will count also meta values? You can limit from the users_table and then left join meta_table, but looks like the result would be same. Please explain with an example. Sep 22, 2015 at 10:09
  • That if I use LIMIT 5 at the end of the query, it will count the first row as user + first meta. But other 4 results will be first user's meta and no other user will be fetched. I want 5 users to be fetched + their metas
    – a-coder
    Sep 22, 2015 at 10:16

2 Answers 2

4

You can try to use subquery. For example

SELECT * FROM meta_table 
         RIGHT OUTER JOIN (SELECT * FROM users_table 
                           WHERE status = 1
                           ORDER BY users_table.id ASC LIMIT 10) as tbl_user 
         ON meta_table.user_id = tbl_user.id
4
  • 1
    Thanks for the snippet. However it now fetches all the meta, not matching users over the limit. Metas related to the first 10 users have got related users data. Then contains only NULL
    – a-coder
    Sep 22, 2015 at 10:24
  • @a-coder: sorry, used incorrect JOIN, please try with RIGHT OUTER JOIN, also updated answer
    – mergenchik
    Sep 22, 2015 at 10:28
  • Almost there: now fetches correctly, but doesn't work with WHERE clauses. For example the second user with status = 1 is the #15. That query doesn't return him even if is in the clauses
    – a-coder
    Sep 22, 2015 at 10:49
  • if you use where on users_table, then add it in subquery, for example change subquery as (SELECT * FROM users_table WHERE status = 1 ORDER BY users_table.id ASC LIMIT 10)
    – mergenchik
    Sep 22, 2015 at 10:51
1

Thanks to @mergenchik to point me on the right direction.

I ended up with a slightly different query to keep users table data at the beginning and be able to join a new table in future

SELECT * FROM 
    (SELECT * FROM users_table ORDER BY id ASC LIMIT 15) as users_table
LEFT OUTER JOIN meta_table 
ON meta_table.user_id = users_table.id

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.