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