简体   繁体   English

连接MySQL中的两个表,其中一个表在另一个表中具有多个值

[英]Joining two tables in MySQL with one having multiple values in the other table

Tools table: 工具表:

id      tool_nr   
687      2902
745      2456
234      3245

Product Table: 产品表:

id      tool_id   something
3432     687       123456
4587     745       254786
4411     687       258956 
4741     234       874455 
8745     745       987445

So, tools table id equals product table tool_id. 因此,工具表ID等于产品表tool_id。

What I would like: 我想要的是:

tool_nr     something
2902        123456
2456        254786
2902        258956
3245        874455
2456        987445

As you can see tools table id may have multiple values in the product table, right know my query is giving me "something" values together separated with commas, but I need to change it and I would like to know what would be the best way to do it? 如您所见,工具表ID在产品表中可能有多个值,正确知道我的查询是给我一些“东西”值,并用逗号分隔,但是我需要更改它,我想知道什么是最好的方法去做吧?

Try this : 尝试这个 :

SELECT t.tool_nr, p.something 
FROM Product p 
JOIN Tools t ON p.tool_id=t.id;
$result = mysql_query("SELECT 
                             t.tool_nr, 
                             p.something 
                       FROM tools t 
                       LEFT JOIN products p 
                       ON p.tool_id = t.id");

From what I gather you want to have the same order of elements as it is for products. 根据我的收集,您希望元素具有与产品相同的顺序。 You could try this command: 您可以尝试以下命令:

$result = mysql_query("SELECT Tools.tool_nr, p.something FROM Product  "
                       ." INNER JOIN Tools"
                       ." ON Product.tool_id = Tools.id"
                       ." ORDER BY Product.id");

It would give you all rows where a tool exists for a given product. 它将为您提供给定产品存在工具的所有行。 If you want to show all products instead and only show the tools where they exist for the appropriate products: 如果要显示所有产品,而仅显示适当产品的工具,则:

$result = mysql_query("SELECT Tools.tool_nr, p.something FROM Product  "
                       ." LEFT JOIN Tools"
                       ." ON Product.tool_id = Tools.id"
                       ." ORDER BY Product.id");

If instead you want to show all Tools and only those products that exist for these tools: 相反,如果您要显示所有工具以及仅显示这些工具存在的那些产品:

$result = mysql_query("SELECT Tools.tool_nr, p.something FROM Tools  "
                       ." LEFT JOIN Product"
                       ." ON Product.tool_id = Tools.id"
                       ." ORDER BY Product.id");

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

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