0

次のようなテーブル構造があります。

mysql> describe post_category_relations;
+-------------+---------+------+-----+---------+----------------+
| Field       | Type    | Null | Key | Default | Extra          |
+-------------+---------+------+-----+---------+----------------+
| relation_id | int(11) | NO   | PRI | NULL    | auto_increment |
| post_id     | int(11) | NO   |     | NULL    |                |
| category_id | int(11) | NO   |     | NULL    |                |
+-------------+---------+------+-----+---------+----------------+
3 rows in set (0.01 sec)

mysql> describe posts;
+---------+--------------+------+-----+---------+----------------+
| Field   | Type         | Null | Key | Default | Extra          |
+---------+--------------+------+-----+---------+----------------+
| post_id | int(11)      | NO   | PRI | NULL    | auto_increment |
| title   | varchar(255) | YES  |     | NULL    |                |
| content | text         | YES  |     | NULL    |                |
| date    | datetime     | YES  |     | NULL    |                |
| active  | tinyint(1)   | YES  |     | NULL    |                |
+---------+--------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)

mysql> describe categories;
+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| cat_id   | int(11)      | NO   | PRI | NULL    | auto_increment |
| cat_name | varchar(255) | YES  |     | NULL    |                |
+----------+--------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

私がやりたいのは、カテゴリ 1 の投稿を選択することです。これが私のクエリですが、ID 2 のカテゴリと ID 21 のカテゴリを分割することはできませんwhere。単一のクエリで実行したい。これまでの私のクエリは次のとおりです。

SELECT posts . * , (
SELECT GROUP_CONCAT( DISTINCT categories.cat_name ) 
FROM categories
LEFT JOIN post_category_relations ON post_category_relations.category_id = categories.cat_id and categories.cat_id = 1
WHERE post_category_relations.post_id = `posts`.post_id
GROUP BY post_category_relations.post_id
) AS category, (
SELECT GROUP_CONCAT( DISTINCT categories.cat_id ) 
FROM categories
LEFT JOIN post_category_relations ON post_category_relations.category_id = categories.cat_id
WHERE post_category_relations.post_id = `posts`.post_id
GROUP BY post_category_relations.post_id
) AS cate_id
FROM (`posts` 
)
HAVING `cate_id` LIKE '%2%'
LIMIT 0 , 30

編集:私の友人がそれを解決しました。結局のところ、私のアプローチは間違っていたと思います:

SELECT posts. * , categories. * 
FROM post_category_relations
INNER JOIN posts ON posts.post_id = post_category_relations.post_id
INNER JOIN categories
ON categories.cat_id = post_category_relations.category_id
WHERE post_category_relations.category_id =2
LIMIT 0 , 30
4

0 に答える 0