3

检查这个小提琴的数据库和表

SELECT p.*
FROM Products p
LEFT JOIN offertran ot 
ON p.prod_id = ot.prod_id
LEFT JOIN Offers o
ON ot.offer_id =  (SELECT id FROM Offers 
                   Where dF<=3 AND dt>=3)

ORDER BY o.id DESC, 
          p.prod_id ASC
LIMIT 20

输出是:

| PROD_ID | CATEGORY_ID | PROD_NAME |  BRAND | PRICE | STATUS |
---------------------------------------------------------------
|      p3 |          c1 |     prod3 | brand3 |  3000 | active |
|      p3 |          c1 |     prod3 | brand3 |  3000 | active |
|      p1 |          c1 |     prod1 | brand1 |  1000 | active |
|      p2 |          c2 |     prod2 | brand2 |  2000 | active |
|      p4 |          c2 |     prod4 | brand1 |  4000 | active |
|      p5 |          c1 |     prod5 | brand2 |  5000 | active |
|      p6 |          c2 |     prod6 | brand3 |  6000 | active |

但是,如您所见,这里p3显示了两次。我不知道为什么..我已经尝试了所有可能的方法,但我找不到任何补救措施.. :(

4

4 回答 4

4

问题在

LEFT JOIN Offers o
ON ot.offer_id =  (SELECT id FROM Offers 
                   Where dF<=3 AND dt>=3)

您将 ot.offer_id 与常量值连接起来(从报价表中选择它们没有任何意义)。

正确的方法:

SELECT p.*
FROM Products p
LEFT JOIN offertran ot 
ON p.prod_id = ot.prod_id
LEFT JOIN Offers o
ON ot.offer_id = o.id AND o.dF<=3 AND o.dt>=3
ORDER BY o.id DESC, 
          p.prod_id ASC
LIMIT 20

看看这个 SQLFiddle

于 2012-10-03T08:39:21.500 回答
1

可能你正在寻找这个。这将只返回一次 p3。您错过了 Second Left Join 条件中的 o.id。

SELECT p.*
FROM Products p
LEFT JOIN offertran ot 
ON p.prod_id = ot.prod_id
LEFT JOIN Offers o
ON o.id =  (SELECT id FROM Offers 
            Where dF<=3 AND dt>=3)

ORDER BY o.id DESC, 
          p.prod_id ASC
LIMIT 20
于 2012-10-03T08:37:45.940 回答
1

可能缺少 'o' 和 'ot' 之间的连接条件:

SELECT p.*
FROM Products p
LEFT JOIN offertran ot 
ON p.prod_id = ot.prod_id
LEFT JOIN Offers o
ON ot.offer_id IN(SELECT id FROM Offers 
               Where dF<=3 AND dt>=3)
**AND ot.offer_id = o.id***
ORDER BY o.id DESC, 
      p.prod_id ASC
LIMIT 20

或者,也许我错过了一些东西,并且没有理解您想通过查询从数据库中获得什么。

于 2012-10-03T08:34:51.450 回答
0

您可能有两条记录在offertranProducts带有 p3 的 PROD_ID。您可以将其更改为SELECT DISTINCT p.* FROM ...,这样任何重复的行都将被忽略。

只是为了看看offertran返回的内容,将您更改select p.*select *

于 2012-10-03T08:31:01.793 回答