简体   繁体   English

当MySQL查询基于相关表中的第二个关系时,如何获得一对多结果?

[英]How to get a one-to-many result when the MySQL query is based on a second relationship in the related table?

I'm a real noob to MySQL and I'm not even certain that the question was worded correctly. 我是MySQL的真正菜鸟,我甚至不确定问题的措词是否正确。

The database has two tables, Products and Feedback. 该数据库有两个表,产品和反馈。 The fields in the Products table are sku and variations. 产品表中的字段是sku和变体。 There can be multiple variations for a single sku. 单个sku可以有多个变体。 The fields in the Feedback table are variation, title, text. 反馈表中的字段是变体,标题,文本。 There is a one-to-many relationship between Products.variations and Feedback.variations. 在Products.variations和Feedback.variations之间存在一对多关系。

The goal is a query that returns the title and text of all Feedback for all of the variations of a single product. 目标是查询,该查询针对单个产品的所有变体返回所有“反馈”的标题和文本。

My code doesn't work. 我的代码不起作用。 In the example below, I want all Feedback when sku='proda'. 在下面的示例中,当sku ='proda'时,我需要所有反馈。

SELECT DISTINCT Products.variations, Products.sku, Feedback.variations, Feedback.title, Feedback.text
WHERE Products.sku='proda'
inner join Products.sku ON Products.variations = Feedback.variations 

This the error: 这个错误:

1064 - You have an error in your SQL syntax; 1064-您的SQL语法有误; ... near 'WHERE Products.sku='proda' ...靠近'WHERE Products.sku ='proda'
inner joi' at line 2 第2行的内部joi'

The literal after an INNER JOIN statement should be a table name, not a column name. INNER JOIN语句后的文字应该是表名,而不是列名。

SELECT DISTINCT Products.variations, Products.sku, Feedback.variations, Feedback.title, Feedback.text
FROM Feedback
INNER JOIN Products
ON Products.variations = Feedback.variations
WHERE Products.sku = 'proda'

WHERE statements go after joins. 加入后在WHERE声明。 The SELECT also needs a FROM . SELECT还需要一个FROM

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM