我正在尝试解决MySQL问题,我有两个表:
-
CATEGORIES
(列:_id、_name) -
POSTS
(列:_id、_category、_title、_text)
POSTS
_category字段是LONGTEXT
的,并且只能使用 implode(",") PHP 函数将多个CATEGORIES
_ID分隔。
我尝试用 PHP 列出 10 个最受欢迎的类别,并在 () 中显示其中的帖子,但没有运气。
我对MySQL不是很熟悉,我只知道如何使用SELECT FROM WHERE ORDER LIMIT,INSERT&UPDATE,所以如果有人能给我一个好的解决方案,我会很高兴。我尝试使用 IN(),但 IN() 需要POSTS
的_category字段像这个"1"、"2"、"3"、"4",现在是没有引号的 1,2,3,4,所以如果有人知道如何将这个字段转换为没有字段类型集的列表,我会很高兴。
您可能希望将关系模型更改为以下内容:
表类别与列:
-
_id
-
_name
带列的表格帖子:
-
_id
-
_title
-
_text
表拥有与列:
-
post_id
(外键) -
category_id
(外键)
POSSESS 关系(表)中的元组表示post_id
属于category_id
类别。
它的
关键词是"多对多"关系,如果可能的话,像马克贝克写的那样重构你的方案。
使用
Dyin 建议的模型,您将使用类似这样的东西按受欢迎程度列出前 10 个类别(假设一个类别的帖子越多,它就越受欢迎):
SELECT
c.*, # get all values for rows in categories
count(p.post_id) AS post_count # here we are counting the posts for each category using a field alias for the count
FROM (
categories AS c, # we are aliasing the tables also to shorten the typing a bit
possess AS p # you could also use aliases to join the same table multiple times
)
WHERE
c.id = p.category_id # link the categories and the possess tables
GROUP BY c.id # without this, the query would just count all posts, this way the result set is separated into groups by category
ORDER BY post_count DESC
LIMIT 10
鉴于你所说的SQL经验,这个查询现在似乎有点过头了,但我认为你可以作为一个学习更多的起点,一如既往,谷歌是你的朋友。首先研究如何使用外键和联接链接表。
我用过这个:
SELECT *, (SELECT COUNT(*) FROM offer WHERE FIND_IN_SET(type._id, offer._type)) AS _count FROM type ORDER BY _count DESC LIMIT 0, 10
目前工作正常,它的表类型(列:_id、_name)和报价(列:..、..、_types、