我试图找到一个查询,该查询可以使用多个共享列以及两个不共享相同值但遵循某种顺序的递增列来联接两个表。我正努力用简单的英语解释这个问题,所以这里有一个例子:

第一个表,项,如下所示:

|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列添加到charges架构,则希望进行回退,这似乎是理想的解决方案。

是否有人对解决此问题的最佳方法有想法?

最佳答案

使用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

09-06 20:17