小型交易系统共有3个表格; USERS , ITEMS 和 TRADES ,交易本身保存在表TRADES(逻辑上足够)中,如下:
column type
========== =====
seller_id int
buyer_id int
item_id int
quantity int
cost int
currency int
我想显示挂起的交易,使用3方式连接将ID映射到表USER和ITEM中的名称。到目前为止我已经:
SELECT
users.name AS seller,
items.id AS item_id,
items.name AS item,
trades.item_id AS trade_id,
trades.quantity AS quantity,
trades.cost AS cost,
trades.currency AS currency
FROM
(trades INNER JOIN users ON trades.seller_id = users.id)
INNER JOIN items ON trades.item_id = items.id
WHERE trades.buyer_id = xxx
第一次连接工作正常,但只要我将结果传递给第二次就失败了;返回零数据。我支持它是一个真正的noobie问题(实际上我希望它是,很容易修复=好)但我看不到它(可能是因为我实际上是这些东西的菜鸟)。
答案 0 :(得分:4)
SELECT
users.name AS seller,
items.id AS item_id,
items.name AS item,
trades.item_id AS trade_id,
trades.quantity AS quantity,
trades.cost AS cost,
trades.currency AS currency
FROM
trades
LEFT JOIN
users
ON
trades.seller_id = users.id
LEFT JOIN
items
ON
trades.item_id = items.id
WHERE trades.buyer_id = xxx
答案 1 :(得分:1)
我认为trades_id需要是trades.item_id
我还建议你使用LEFT JOIN而不是INNER JOIN,如果你想在没有匹配的情况下触发错误,只使用INNER JOIN。使用LEFT JOIN时,它总是返回数据,当第二个表中没有匹配时也是如此。请参阅:http://www.w3schools.com/Sql/sql_join.asp