简体   繁体   English

多个联接到两个持有fk的表

[英]multiple joins to two tables holding fk's

I'm facing a strange behavior that I must be interpreting wrong, Given that computers always execute exactly what you tell them to, I must be telling it wrong :) 我正面临一种奇怪的行为,我必须将其解释为错误,鉴于计算机始终严格执行您告诉他们的操作,因此我必须告诉它错误的信息:)

Use Case : 用例:
I have a table called orders_details that consists of columns of interest, both foreign keys, order_id and product_id . 我有一个名为orders_details的表,该表包含感兴趣的列,包括外键, order_idproduct_id

I also have a table called orders which has a PK of order_id and a table called product_details that has a PK of product_id column. 我也有一个名为orders的表,它具有order_idPK ,还有一个名为product_details的表,它具有product_id列的PK

The requirement : 要求 :

Select all orders with their respective order detail and product detail. 选择所有带有其各自的订单详细信息和产品详细信息的订单。

What I tried : 我试过了

SELECT ord.shipping_ids, ord.order_id, ord.firstname, ord.lastname, ord.order_id,
ord.payment_id, det.product_id, ord.timestamp, prd.product

FROM  `cscart_orders` AS ord  

LEFT JOIN cscart_order_details AS det ON ord.order_id = det.order_id

LEFT JOIN cscart_product_details AS prd ON prd.product_id = det.product_id

Now this results is getting null for all the product_details columns, so I don't get what I need. 现在,所有product_details列的结果都为null ,所以我没有得到所需的东西。

If i replace the 2nd join to an inner join, I get corrupted data (multiple copies of each row without any logical order that I've noticed). 如果我将第二个联接替换为内部联接,则会得到损坏的数据(每行的多个副本,而我没有注意到任何逻辑顺序)。

So, What am I missing? 所以,我想念什么? Isn't this how joins should work? 这不是联接应该起作用的方式吗?

Edit : 编辑:

http://sqlfiddle.com/#!2/f98463/2 -sqlfiddle, Never knew a fiddle exists for sql, sorry for not posting it in the first place. http://sqlfiddle.com/#!2/f98463/2 -sqlfiddle,不知道sql是否存在小提琴,很抱歉没有首先发布它。

2nd edit : 第二次编辑:

my DB tables had data integrity issues :( someone didn't properly set FK's and PK's, My original query does indeed work on a sample data, Thanks for pointing me to the right place to double check myself 我的数据库表存在数据完整性问题:(有人未正确设置FK和PK,我的原始查询确实对示例数据有效,感谢您将我指向正确的位置来仔细检查自己

Your given query working fine on sql fiddle If you give expected output so we can help you. 您给定的查询在sql小提琴上工作正常如果您提供期望的输出,那么我们可以为您提供帮助。

SELECT ord.shipping_ids, ord.order_id, ord.firstname, ord.lastname, ord.order_id,
ord.payment_id, det.product_id, ord.timestamp, prd.product

FROM  `cscart_orders` AS ord  

LEFT JOIN cscart_order_details AS det ON ord.order_id = det.order_id

LEFT JOIN cscart_product_details AS prd ON prd.product_id = det.product_id

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

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