how do I write this wp_query select statement?

If you can formulate problematic part of your request as WP query you can run it and look at $wpdb->last_query to see generated SQL. This is usually easiest way to have a starting point and something to customize further.

error code: 523