php - Match 2 columns from the same table to the same single column in another table (total of 3 joins)
问题描述
I have 3 tables.
sheets TABLE
sheet_id
brand_id
sheet_color
sheet_code
adhesive_id_1
adhesive_id_2
adhesive_id_3
factor_1
factor_2
factor_3
sheet_brands TABLE
brand_id
brand_name
surface_type_id
adhesives TABLE
adhesive_id
match_code
match_name
I need to match:
1) sheets.brand_id to sheet_brands.brand_id to get the brand_name
2) sheets.adhesive_id_1 to adhesives.adhesive_id to get the match_code and match_name
3) sheets.adhesive_id_2 to adhesives.adhesive_id to get the match_code and match_name
I have spent awhile searching and have not found a solution that works. I believe this type of JOIN is unique because I need to match 2 columns from the same table to the same single column in another table.
This is the closest I came to solving the problem BUT it only matches the first adhesive_id_1. It does not match adhesive_id_2 or adhesive_id_3.
$sql = "SELECT sheet_color, sheet_code, factor_1, factor_2, brand_name, match_code, match_name FROM sheets LEFT JOIN sheet_brands ON sheet_brands.brand_id = sheets.brand_id LEFT JOIN adhesives ON adhesives.adhesive_id = sheets.adhesive_id_1";
解决方案
您必须加入表adhesives
两次才能同时获得match_code
s 和match_name
s:
SELECT s.sheet_color, s.sheet_code, s.factor_1, s.factor_2,
b.brand_name,
a1.match_code match_code1, a1.match_name match_name1,
a2.match_code match_code2, a2.match_name match_name2
FROM sheets s
LEFT JOIN sheet_brands b ON b.brand_id = s.brand_id
LEFT JOIN adhesives a1 ON a1.adhesive_id = s.adhesive_id_1
LEFT JOIN adhesives a2 ON a2.adhesive_id = s.adhesive_id_2
为表使用别名并使用这些别名限定列名。
如果您还想要match_code
and match_name
foradhesive_id_3
您将需要再加入:
SELECT s.sheet_color, s.sheet_code, s.factor_1, s.factor_2,
b.brand_name,
a1.match_code match_code1, a1.match_name match_name1,
a2.match_code match_code2, a2.match_name match_name2,
a3.match_code match_code3, a3.match_name match_name3
FROM sheets s
LEFT JOIN sheet_brands b ON b.brand_id = s.brand_id
LEFT JOIN adhesives a1 ON a1.adhesive_id = s.adhesive_id_1
LEFT JOIN adhesives a2 ON a2.adhesive_id = s.adhesive_id_2
LEFT JOIN adhesives a3 ON a3.adhesive_id = s.adhesive_id_3
推荐阅读
- android - Kotlin 多态序列化(字符串数组和对象数组)
- tensorflow - 如何创建自定义损失函数,将 RNN 的中间训练输出(张量 y_pred)馈送到另一个预定义的 RNN?
- ruby-on-rails - 使用 Ruby 验证 Web Crypto SubtleCrypto 密钥签名
- julia - 朱莉娅:重新解释的逆(相反)是什么?
- python - 如何在python中的kers中添加LSTM中的dropout和attention
- reactjs - 如何在 React 中使用 JWT 令牌实现私有路由
- laravel - 如何在父类别下直接显示子类别?
- python - 如何从 4 层嵌套字典中调用最深的嵌套值?
- amazon-web-services - 在 AWS SSL Activate 上使用时出现错误?
- sql - 如何显示每个部门每个职位的员工人数