0

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.

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?

4

3 回答 3

0

尝试这个 :

SELECT t.tool_nr, p.something 
FROM Product p 
JOIN Tools t ON p.tool_id=t.id;
于 2012-08-02T07:56:32.793 回答
0
$result = mysql_query("SELECT 
                             t.tool_nr, 
                             p.something 
                       FROM tools t 
                       LEFT JOIN products p 
                       ON p.tool_id = t.id");
于 2012-08-02T07:57:41.933 回答
0

据我所知,您希望拥有与产品相同的元素顺序。你可以试试这个命令:

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

它将为您提供给定产品存在工具的所有行。如果您想改为显示所有产品,并且只显示适用于相应产品的工具:

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

相反,如果您想显示所有工具,并且只显示这些工具存在的那些产品:

$result = mysql_query("SELECT Tools.tool_nr, p.something FROM Tools  "
                       ." LEFT JOIN Product"
                       ." ON Product.tool_id = Tools.id"
                       ." ORDER BY Product.id");
于 2012-08-02T08:22:06.757 回答