【WordPress】$wpdbから取得するsql文

global $wpdb;

$query = "
    SELECT DISTINCT p.*
    FROM {$wpdb->posts} p
    INNER JOIN {$wpdb->term_relationships} tr ON (p.ID = tr.object_id)
    INNER JOIN {$wpdb->term_taxonomy} tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id)
    INNER JOIN {$wpdb->terms} t ON (tt.term_id = t.term_id)
    WHERE p.post_type = 'post'
    AND p.post_status = 'publish'
    AND t.name = 'memo'
    AND EXISTS (
        SELECT 1
        FROM {$wpdb->term_relationships} tr2
        INNER JOIN {$wpdb->term_taxonomy} tt2 ON (tr2.term_taxonomy_id = tt2.term_taxonomy_id)
        INNER JOIN {$wpdb->terms} t2 ON (tt2.term_id = t2.term_id)
        WHERE tr2.object_id = p.ID
        AND t2.name = 'memo2'
    )
		ORDER BY p.post_date DESC
";

$results = $wpdb->get_results($query);
var_dump($results);

?>

<table style="margin:2em;">
  <tr>
    <th>ID</th>
    <th>タイトル</th>
    <th>カテゴリ</th>
  </tr>
  <?php
  foreach ($results as $post) {
    $post_ID = $post->ID;
    echo ' 投稿ID:' . $post_ID . ' カテゴリー:';
    $cats = get_the_category($post_ID);
    // var_dump($cats);
    // if (isset($cat[0]->cat_ID))  $cat_id = $cat[0]->cat_ID;
    // echo $cat . "<br>";
    foreach ($cats as $cat) {
      echo $cat->name . ",";
    }
    echo "<br>";
  };