如果表列中没有重叠,则使用标准值

时间:2014-10-01 13:18:16

标签: mysql sql

我有一个表ce_relations和一个表ce_values,我希望将它们组合成一个表ce_combined_values。 ce_combined_values表应具有与ce_relations完全相同的行数。但是,下面描述的查询仅返回ce_values.user_id列中user_id和friend_id存在的行。我试图通过使用IFNULL语句解决这个问题,但我想在WHERE clausule中还缺少一个额外的条件......欢迎任何帮助!

INSERT INTO ce_combined_values (user_id, friend_id, relation_degree, user_value, friend_value, relation_value)
SELECT a.user_id, a.friend_id, a.relation_degree,  IFNULL(b.1d_value, 0)  as user_value, IFNULL(c.1d_value, 0) as friend_value, Least(b.1d_value, c.1d_value) as relation_value
FROM  ce_relations a, ce_values b, ce_values c
WHERE a.relation_degree = 1 AND b.user_id = a.user_id AND c.user_id = a.friend_id AND b.user_id <> c.user_id

Union all

//same select query is used for relation_degree 2 with 2d_values and relation_degree 3 with 3d_values.

编辑:

例如,这就是我想要实现的目标:

表ce_relations:

+---------+-----------+-----------------+
| user_id | friend_id | relation_degree |
+---------+-----------+-----------------+
|       1 |         3 |               1 |
|       2 |         1 |               1 |
|       3 |         4 |               1 |
+---------+-----------+-----------------+

表ce_values:

+---------+----------+----------+----------+
| user_id | 1d_value | 2d_value | 3d_value |
+---------+----------+----------+----------+
|       1 |        5 |       10 |       33 |
|       2 |       10 |       12 |       44 |
|       3 |       20 |       13 |       55 |
+---------+----------+----------+----------+

应该成为ce_combined值(为了便于阅读,删除了relation_degree和relation_value)

+---------+-----------+------------+--------------+
| user_id | friend_id | user_value | friend_value |
+---------+-----------+------------+--------------+
|       1 |         3 |          5 |           20 |
|       2 |         1 |         10 |            5 |
|       3 |         4 |         20 |            0 |
+---------+-----------+------------+--------------+

但当前返回(缺少friend_id = 4的行,因为它在ce_values中不存在)

+---------+-----------+------------+--------------+
| user_id | friend_id | user_value | friend_value |
+---------+-----------+------------+--------------+
|       1 |         3 |          5 |           20 |
|       2 |         1 |         10 |            5 |
+---------+-----------+------------+--------------+ 

1 个答案:

答案 0 :(得分:0)

如果我正确理解您的问题,您需要左键加入您的表格。而且我不认为你需要UNION所有相同的查询三次只有一个不同的过滤条件。

也许这有助于你:

SELECT a.user_id, a.friend_id, a.relation_degree, 
       IFNULL(b.value, 0) as user_value, 
       IFNULL(c.value, 0) as friend_value, 
       Least(b.value, c.value) as relation_value
  FROM ce_relations a
  LEFT
  JOIN ce_values b
    ON a.user_id = b.user_id 
  LEFT
  JOIN ce_values c
    ON a.friend_id = c.user_id
   AND b.user_id <> c.user_id
 WHERE a.relation_degree IN (1, 2, 3)