Search code examples
mysqlsqldatabaseroundcube

Query data in one table based on IDs from another


I'm trying to export data from Roundcube, and it has 2 tables that I need, the users and contacts. Currently I'm using this to filter the users:

 SELECT `user_id` FROM `users` WHERE `username` LIKE "%mysite.com%"

But how do I export data from the contacts table, where the user_id matches the above filtered list of user_ids? Do I have to use temporary tables? I've never done a join. I don't want a pretty listing of the 2 tables joined, I want to export the data using a SELECT clause to filter it and re-import it, so I need the data in the original format.


Solution

  • You can also use sub-queries:

    SELECT *
    FROM `contacts`
    WHERE `user_id` IN (
        SELECT `user_id` FROM `users` WHERE `username` LIKE "%mysite.com%"
    )