[英]Order results from one MySQL table by another, which is saving multiple values into the order field
我正在尝试解决MySQL问题,我有两个表:
CATEGORIES
(专栏:_id,_name) POSTS
(COLUMNS:_id,_category,_title,_text) 在_category字段POSTS
是LONGTEXT
和可以有多个CATEGORIES
_ID的分离仅通过使用内爆(“”)PHP函数。
我尝试用PHP列出10个最受欢迎的类别,并在()中显示其中的帖子,但没有运气。
我不熟悉MySQL,我只知道如何使用SELECT FROM WHERE ORDER LIMIT,INSERT和UPDATE所以如果有人能给我一个很好的解决方案,我会很高兴。 我试图用IN(),但在()需要的_category字段POSTS
是这样“1”,“2”,“3”,“4”,现在它的1,2,3,4-没有引号,所以,如果有人知道如何在不使用FIELD TYPE SET的情况下将此字段转换为列表,我将非常高兴。
您可能希望将关系模型更改为以下内容:
带有列的表类别:
_id
_name
表格列与列:
_id
_title
_text
表有POSHESS:
post_id
(外键) category_id
(外键) POSSESS关系(表)中的元组表示post_id
属于category_id
类别。
关键词是“多对多”的关系,如果可能的话,像Mark Baker写的那样重构你的计划。
使用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)和offer(列:..,..,_ type,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.