左连接具有唯一值

时间:2016-06-30 12:46:09

标签: mysql

我希望从第一个表中获取所有值以及第二个表中的连接值。

表1是fee_category,其中包含字段:

id | Category
1  | A
2  | B
3  | C
4  | D

表2是带字段的费用:

id | std_id | particularID | CategoryID | assign | amount
1  | 1      | 1            | 1          | 0      | 1000  
2  | 1      | 1            | 2          | 1      | 12000  
3  | 1      | 2            | 3          | 0      | 3000  
4  | 1      | 2            | 4          | 0      | 10  
5  | 2      | 1            | 2          | 0      | 100  
6  | 2      | 2            | 3          | 0      | 120  

基本表是" fee_category"从中我需要所有的价值观加入" fee_charge"从哪里我需要值或NULL为特定的std_id和特定ID

SELECT fee_category.id, fee_category.Category, fee_charge.std_id
, fee_charge.particularID, fee_charge.CategoryID, fee_charge.assign, fee_charge.amount FROM fee_category
LEFT join fee_charge on fee_category.id=fee_charge.CategoryID
where (fee_charge.std_id = 1 OR fee_charge.std_id IS NULL) 
AND (fee_charge.particularID = 1 OR fee_charge.particularID IS NULL) 
group By fee_category.id
order By fee_charge.assign DESC

这里我试图获得所有类别的std_id = 1和特定ID = 1

正确的结果应该是

id | Category | std_id | particularID | CategoryID | assign | amount
1  | A         | 1      | 1            | 1          | 0      | 1000
1  | B         | 1      | 1            | 2          | 1      | 12000
1  | C         | 1      | NULL         | NULL       | NULL   | NULL
1  | D         | 1      | NULL         | NULL       | NULL   | NULL

我正在尝试上述查询的各种版本,但没有得到正确的结果。请帮忙

2 个答案:

答案 0 :(得分:0)

SELECT fee_category.id
, fee_category.Category
, X.std_id
, X.particularID
, X.CategoryID
, X.assign
, X.amount
 FROM fee_category
LEFT JOIN 
(SELECT * FROM fee_charge
     WHERE fee_charge.std_id = 1 
     AND fee_charge.particularID = 1) AS X 
     ON x.CategoryID = fee_category.id

答案 1 :(得分:0)

当小提琴与问题不匹配时很难理解,所以我可能会误解,但也许你是在追求这样的事情......

SELECT x.id
     , z.category
     , x.std_id
     , y.particularID
     , y.categoryID
     , y.assign
     , y.amount 
  FROM fee_charge x
  LEFT
  JOIN fee_charge y
    ON y.id = x.id
   AND y.particularID = 1
  JOIN fee_category z
    ON z.id = x.categoryID
 WHERE x.std_id = 1;