0

我尝试了其他几个答案,但我仍然无法解决这个问题。也许如果我的具体问题得到解决,我可以理解如何加入三个表。

我有这些表:

invoice
id - 

invoiceItem
id - invId - itemId - discode

item
id - name - cid(categoryID) - price - memprice - attendee_price

category
id - catName

我查询发票并获得 id,然后运行一个 while 循环:获取发票项目列表、这些项目的详细信息(按 id)和类别(按 id)。

这是我正在尝试的查询,但我挂断了连接和 where 子句

while ($r = mysql_fetch_assoc($invoice_query){      
//my invoice id is $r['id']

    $iQ = mysql_query("SELECT 
          item.id, item.cid, item.name, item.memprice, item.attendee_price, item.price,
          invoiceItem.discode, 
          categories.id, categories.catName
          FROM invoiceItem 
          INNER JOIN categories ON item.cid=categories.id 
          INNER JOIN item ON ?????? 
          WHERE invoiceItem.id='$r[id]'");
}
4

1 回答 1

2

ON 条件INNER JOINS通常包括 leftTable.foreignKey = rightTable.primaryKey...在您的情况下,您需要为 invoice 表添加连接,以便将其主键与 invoiceItem 表中的外键匹配(invoice.id = invoiceItem.invId)

SELECT 
          item.id, item.cid, item.name, item.memprice, item.attendee_price, item.price,
          invoiceItem.discode, 
          categories.id, categories.catName
          FROM invoiceItem 
          INNER JOIN item ON item.id = invoiceItem.itemId 
          INNER JOIN categories ON item.cid=categories.id 
          INNER JOIN invoice ON invoice.id = invoiceItem.invId
          WHERE invoice.id='$ir[id]'
于 2013-07-12T21:46:20.027 回答