我尝试了其他几个答案,但我仍然无法理解这一点。也许如果我的具体问题得到解决,我可以理解如何加入三个表格。
我有这些表格:
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]'");
}
答案 0 :(得分:2)
INNER JOINS
的ON条件通常包含
leftTable.foreignKey = rightTable.primaryKey
...在您的情况下,您需要为发票表添加联接,以便将其主键与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]'