MySQL连接问题
你好,我正在努力编写一个特定的 MySQL 连接查询。
我有一个包含产品数据的表,每个产品可以属于多个类别。使用链接表可以满足这种 m:m 关系。
对于这个特定的查询,我希望检索属于给定类别的所有产品,但对于每个产品记录,我还想返回该产品所属的其他类别。
理想情况下,我希望在类别表上使用内部联接来实现此目的,而不是对每个产品记录执行额外的查询,这将是非常低效的。
我的简化架构设计大致如下:
产品表:
product_id, name, title, description, is_active, date_added, publish_date, etc....
类别表:
category_id, name, title, description, etc...
product_category 表:
product_id, category_id
我编写了以下查询,它允许我检索属于指定category_id 的所有产品。然而,我真的很难弄清楚如何检索产品所属的其他类别。
SELECT p.product_id, p.name, p.title, p.description
FROM prod_products AS p
LEFT JOIN prod_product_category AS pc
ON pc.product_id = p.product_id
WHERE pc.category_id = $category_id
AND UNIX_TIMESTAMP(p.publish_date) < UNIX_TIMESTAMP()
AND p.is_active = 1
ORDER BY p.name ASC
我很乐意检索与每个返回的产品行相关的类别 ID,因为我将所有类别数据存储在一个对象中,而我的应用程序代码可以处理其余的事情。
非常感谢,
理查德
Hi i'm struggling to write a particular MySQL Join Query.
I have a table containing product data, each product can belong to multiple categories. This m:m relationship is satisfied using a link table.
For this particular query I wish to retrieve all products belonging to a given category, but with each product record, I also want to return the other categories that product belongs to.
Ideally I would like to achieve this using an Inner Join on the categories table, rather than performing an additional query for each product record, which would be quite inefficient.
My simplifed schema is designed roughly as follows:
products table:
product_id, name, title, description, is_active, date_added, publish_date, etc....
categories table:
category_id, name, title, description, etc...
product_category table:
product_id, category_id
I have written the following query, which allows me to retrieve all the products belonging to the specified category_id. However, i'm really struggling to work out how to retrieve the other categories a product belongs to.
SELECT p.product_id, p.name, p.title, p.description
FROM prod_products AS p
LEFT JOIN prod_product_category AS pc
ON pc.product_id = p.product_id
WHERE pc.category_id = $category_id
AND UNIX_TIMESTAMP(p.publish_date) < UNIX_TIMESTAMP()
AND p.is_active = 1
ORDER BY p.name ASC
I'd be happy just retrieving the category id's releated to each returned product row, as I will have all category data stored in an object, and my application code can take care of the rest.
Many thanks,
Richard
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您将使用对product_category 表的内部联接,在那里进行左联接是没有意义的,因为您在条件中使用其中的值。然后,您对 Product_category 表执行左连接以获取其他类别,并连接数据的类别:
You would use an inner join to the product_category table, doing a left join there is pointless as you are using the value from it in the condition. Then you do a left join on the product_category table to get the other categories, and join in the categories for the data: