根据具有不同值

时间:2017-08-03 17:08:02

标签: mysql sql join

我正在尝试查找可以使用多个共享列加入两个表的查询,以及两个不会共享相同值但不遵守某些顺序的递增列。我正在努力用简单的英语解释这个问题,所以这里有一个例子:

第一个表格,项目如下:

|id|user |period   |item_id|
|--|-----|---------|-------|
|01|1234 |January  |1      |
|02|1234 |January  |2      |
|03|1234 |January  |3      | 
|04|1234 |February |1      |
|05|1234 |February |2      |
|--|-----|---------|-------|

我想加入桌子,收费,如:

|id|user |period   |charge_id|
|--|-----|---------|---------|
|01|1234 |January  |1072     |
|02|1234 |January  |1073     |
|03|1234 |January  |1074     |
|04|1234 |February |567      |
|05|1234 |February |570      |
|--|-----|---------|---------|

我的目标是找到一个导致以下结果的查询:

|id|user |period   |charge_id|item_id|
|--|-----|---------|---------|-------|
|01|1234 |January  |1072     |1      |
|02|1234 |January  |1073     |2      |
|03|1234 |January  |1074     |3      |
|04|1234 |February |567      |1      |
|05|1234 |February |570      |2      |
|--|-----|---------|---------|-------|

我考虑过的一个解决方案是使用临时表或子查询来订购费用,并以我可以直接加入item_id的方式对其进行编号。

CREATE TEMPORARY TABLE numbered_charges AS
  SELECT @row_num:=IF(@last_user=user AND 
                      @last_period=period, 
                      @row_num+1, 1) AS charge_number, 
         @last_user:=user as user, 
         @last_period:=period as period,
         charge_id
  FROM charges
;

SELECT charges.*, items.item_id FROM numbered_charges AS charges
JOIN items ON (charges.charge_number = items.item_id)

但是,我担心这不是一个有效的解决方案。这是一个将作为数据完整性测试的一部分定期运行的查询,因此避免不必要的预处理非常重要。如果我建议将charge_number列添加到计费模式中,我希望能够进行回拨,这似乎是理想的解决方案。

有没有人想过解决这个问题的最佳方法?

2 个答案:

答案 0 :(得分:0)

使用AND运算符帮助加入多个列吗?

SELECT 
T1.id,
T1.user,
T1.period,
T2.charge_id,
T1.item_id
FROM Table1 AS T1
LEFT JOIN Table2 AS T2 ON T1.id=T2.id
AND T1.user=T2.user
AND T1.period=T2.period

答案 1 :(得分:0)

Select id,
user,
period,
charge_id,
item_id
From items
Left join charges on(items.id = charges.id)