【问题标题】:How to return multiple rows in one to many relationship如何以一对多关系返回多行
【发布时间】:2021-01-16 11:09:10
【问题描述】:

我必须在数据库中使用名称为客户的表和车辆都以一对多的关系连接。客户有两条记录,customer_id=1 和 2,车辆有两条记录,customer_id=1,映射到 vehicle_id=1 和 2, customer_id=2 映射到 vehicle_id=3 客户表

╦══════════════╦════════════════════╗
║ customer_id  ║       name         ║
╬══════════════╬════════════════════╣
║           1  ║      pranav        ║
║           2  ║      akshay        ║
╩══════════════╩════════════════════╝

车辆表

╦══════════════╦════════════════════╗═════════════╗
║  vehicle_id  ║    vehicle_name    ║customer_id  ║      | 
╬══════════════╬════════════════════╣═════════════║      
║           1  ║      activa        ║    1        ║
║           2  ║      access        ║    1        ║
║           3  ║      bullet        ║    2        ║
╩══════════════╩════════════════════╝═════════════╝

我收到了

╦══════════════╦════════════════════╗═════════════╗
║  vehicle_id  ║    vehicle_name    ║    name     ║
╬══════════════╬════════════════════╣═════════════║      
║           1  ║      activa        ║   pranav    ║
║           3  ║      bullet        ║   akshay    ║
╩══════════════╩════════════════════╝═════════════╝

预期输出----

╦══════════════╦════════════════════╗═════════════╗
║  vehicle_id  ║    vehicle_name    ║    name     ║
╬══════════════╬════════════════════╣═════════════║      
║           1  ║      activa        ║   pranav    ║
║           2  ║      access        ║   pranav    ║
║           3  ║      bullet        ║   akshay    ║
╩══════════════╩════════════════════╝═════════════╝

我正在使用这个查询

SELECT vehicle_id,vehicle_name,customers.name 
FROM customers,vehicles 
WHERE customers.customer_id=vehicles.vehicle_id

【问题讨论】:

  • 您使用的是什么查询?这看起来像一个简单的join
  • 这是查询 SELECT vehicle_id,vehicle_name,customers.name from customers,vehicles WHERE customers.customer_id=vehicles。车辆ID

标签: mysql sql join foreign-keys relationship


【解决方案1】:

永远不要FROM 子句中使用逗号。 始终使用正确、明确、标准、可读的JOIN语法。

你的问题是你有错误的JOIN 条件。你想要:

select v.vehicle_id, v.vehicle_name, c.name
from customers c join 
     vehicles v
     on c.customer_id = v.customer_id;

注意事项:

  • 当您有多个表引用时,在查询中限定所有列名称。
  • 使用表别名,以便查询更易于编写和阅读。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-26
    • 2019-07-24
    • 2018-06-22
    • 1970-01-01
    • 2014-10-05
    • 2018-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多