mySQL查询返回INNER JOIN的重复结果

时间:2013-12-02 01:30:23

标签: php mysql sql

我需要一些mySQL查询的帮助,我在我的php脚本中使用。似乎我对INNER JOIN的工作方式感到有些困惑。

SELECT * FROM CART_CARD
INNER JOIN INVOICE ON CART_CARD.cartID = INVOICE.cart_invoice_id
INNER JOIN PURCHASE_CARD ON PURCHASE_CARD.invoiceID = INVOICE.ID
WHERE CART_CARD.cardEmail = 'info@test.com'
AND PURCHASE_CARD.ID BETWEEN 26118 AND 26620

所以有3个表 - CART_CARD,INVOICE和PURCHASE_CARD。

PURCHASE_CARD有invoiceID,最高可达INVOICE.ID。 INVOICE有一张现场卡cart_invoice_id,最多可与CART_CARD.cartID匹配。

我正在获得结果,但看起来结果是CART_CARD中的行加倍和三倍。我的查询是否正确?

结果我从CART_CARD回来了。请记住,ID是唯一的主要字段。我省略了其余的字段,因为它是敏感信息:

enter image description here

2 个答案:

答案 0 :(得分:2)

从CART_CARD中选择DISTINCT。仅显示唯一记录。

答案 1 :(得分:1)

SELECT * FROM CART_CARD CC, INVOICE INV, 
 (
 SELECT * FROM PURCHASE_CARD 
 WHERE ID BETWEEN 26118 AND 26620
 AND invoiceID = INV.ID 
 LIMIT 1
 ) PRC
WHERE CC.cartID = INV.cart_invoice_id
AND CC.cardEmail = 'info@test.com'
AND PRC.invoiceID = INV.ID