3个表上的SQL查询从一个获取列并将其用于其他

时间:2015-03-18 03:05:27

标签: sql multiple-tables

我有一个表commission,正在从函数中调用。它由user_id选中,并且会有一些名为sale_product_id的列。此列与另一个表格绑定:sale_product,其中包含另一列sale_id。现在有一个最后一个表sale,它有id。

目前,这就是我所拥有的:

SELECT
    c.amount
FROM 
    commission AS c, 
    sale_product AS sp,
    sale AS s
WHERE 
    c.user_id = '[id]' AND
    c.sale_product_id = sp.id AND
    s.is_paid = 1 AND 
    (s.upline_user_id = c.user_id OR sp.sale_id = s.id)

我应该返回6行,但有21行。我做错了什么?

OUTPUT期望(如果我做SELECT c.* ...):

id   |   sale_product  | user_id |   amount    |
#    |      466        |   3     |    3.99     |
#    |      123        |   3     |    2.99     |

我得到的是重复(我认为因为其他表格看到销售产品ID并做一些时髦的事情)

id   |   sale_product  | user_id |   amount    |
#    |      466        |   3     |    3.99     |
#    |      123        |   3     |    2.99     |
#    |      466        |   3     |    3.99     |
#    |      123        |   3     |    2.99     |
#    |      466        |   3     |    3.99     |

#| 123 | 3 | 2.99 |

我对SQL进行了一些更改,而且我几乎完成了。

这就是我所拥有的:

SELECT 
DISTINCT c.id, c . * , s . * 
FROM 
commission AS c, sale_product AS sp, sale AS s
WHERE
sp.id = c.sale_product_id
AND s.id = sp.sale_id
AND s.is_paid =  '1'
AND sp.cron_executed =  '1'
AND s.upline_user_id = c.user_id
AND c.user_id =  '3'

当我执行此查询时,尤其是s.upline_user_id = c.user_id行时,它只给出了一个查询。这是对的。当我删除该行时,我会获得所有6行。这正确。但是,当我尝试这样做时:

SELECT 
DISTINCT c.id, c . * , s . * 
FROM 
commission AS c, sale_product AS sp, sale AS s
WHERE
sp.id = c.sale_product_id
AND s.id = sp.sale_id
AND s.is_paid =  '1'
AND sp.cron_executed =  '1'
AND s.upline_user_id <> c.user_id
AND c.user_id =  '3'

我得到一个空结果。怎么会?即使我将行更改为s.upline_user_id <> '3',(btw应该给我5行),也给我null。

任何?

1 个答案:

答案 0 :(得分:0)

您在连接上的OR运算符可能会导致重复数据,因为两者都得到满足。如果在不满足条件时使用OR作为后备,请考虑使用CASE语句,如果可能的话。首先测试最可能的条件的存在,ELSE是你的后备。

AND CASE 
       WHEN (a IS NOT NULL AND b IS NOT NULL) 
         THEN (a = b) 
         ELSE (c = d) 
    END

如果要测试字符串,请测试NULL和长度为零。

希望它有所帮助!