【问题标题】:MYSQL- select and join multiple tables into one JSONMYSQL- 选择多个表并将其连接到一个 JSON 中
【发布时间】:2020-04-13 14:36:07
【问题描述】:

你能告诉我如何解决这个问题吗? 我有 3 个数据库表。

  1. 网络。
  2. 产品。
  3. cmets.

在我添加“cmets”表之前查询看起来像这样(按预期工作):

SELECT networks.*, products.product, products.type 
FROM products 
JOIN networks ON products.id=networks.product_Id

现在我尝试使用附加表对其进行修改,但它不起作用:

SELECT 
    networks.*, 
    products.product, 
    products.type, 
    comments.id AS comment_Id, 
    comments.newLine, 
    comments.lineComment AS comment, 
    comments.topComment, 
    comments.bottomComment 
JOIN networks ON products.id=networks.product_Id, 
ON comments.id=networks.comment_Id

如何解决这个问题?

感谢帮助:)

【问题讨论】:

  • 什么不起作用?你忽略了解释。你也没有解释你想要什么。

标签: mysql sql join select multiple-tables


【解决方案1】:

您加入 networks 表的条件为 products.id=networks.product_Id 但是对于 cmets 表,您指定了条件 cmets.id=networks.comment_Id 但您忘记加入 cmets 表。

试试

 SELECT networks.*, 
    products.product, 
    products.type, 
    comments.id AS comment_Id, 
    comments.newLine, 
    comments.lineComment AS comment, 
    comments.topComment, 
    comments.bottomComment 
    FROM products
    JOIN networks ON products.id=networks.product_Id
    JOIN comments ON comments.id=networks.comment_Id

【讨论】:

    【解决方案2】:

    我认为这是您所追求的语法:

    SELECT 
        n.*, 
        p.product, 
        p.type,
        c.id AS comment_id, 
        c.newLine, 
        c.lineComment AS comment, 
        c.topComment, 
        c.bottomComment 
    FROM products p
    INNER JOIN networks n ON p.id = n.product_id
    INNER JOIN comments c ON c.id = n.comment_id
    

    即:多连接的语法为FROM ... JOIN ... ON ... JOIN ... ON ...

    请注意,使用表别名可以缩短查询并使其更易于读写。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-12
      • 1970-01-01
      • 2021-08-22
      • 2016-02-17
      • 2012-10-07
      相关资源
      最近更新 更多