我有一个SQL语法问题。
以下是我的表格:
default_caps:
+-------+------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------+------+-----+---------+----------------+
| idx | int(11) | NO | PRI | NULL | auto_increment |
| tab | int(11) | NO | | NULL | |
| cap | tinyint(1) | NO | | 0 | |
| value | double | YES | | NULL | |
+-------+------------+------+-----+---------+----------------+
convertEntries:
+----------------+------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------+------------+------+-----+---------+----------------+
| idx | int(11) | NO | PRI | NULL | auto_increment |
| convertTable | int(3) | NO | | 0 | |
| convertEntry | int(2) | NO | | 0 | |
| cap | tinyint(1) | NO | | 1 | |
| capTable | int(2) | NO | | 1 | |
+----------------+------------+------+-----+---------+----------------+
我想从convertEntries中选择行,并且在结果的每一行中,我想要包含default_caps.value,使default_caps.tab等于convertEntries.capTable,而default_caps.cap等于convertEntries.cap。
因此,如果default_caps看起来像这样:
+-----+-----+-----+---------+
| idx | tab | cap | value |
+-----+-----+-----+---------+
| 1 | 1 | 0 | 8650.75 |
| 2 | 1 | 1 | 50 |
| 3 | 1 | 7 | 350 |
| 2 | 2 | 0 | 9000 |
| 2 | 2 | 1 | 100 |
| 3 | 2 | 7 | 200 |
+-----+-----+-----+---------+
convertEntries看起来像这样(省略了一些列):
+-----+----------+-----+
| idx | capTable | cap |
+-----+----------+-----+
| 1 | 1 | 1 |
| 2 | 1 | 1 |
| 3 | 1 | 1 |
| 4 | 1 | 1 |
| 5 | 1 | 1 |
| 6 | 1 | 1 |
| 7 | 1 | 7 |
| 8 | 1 | 7 |
| 9 | 1 | 7 |
| 10 | 1 | 0 |
| 11 | 1 | 0 |
| 12 | 1 | 0 |
+-----+----------+-----+
我想要一个这样的结果:
+-----+----------+-----+---------+
| idx | capTable | cap | value |
+-----+----------+-----+---------+
| 1 | 1 | 1 | 50 |
| 2 | 1 | 1 | 50 |
| 3 | 1 | 1 | 50 |
| 4 | 1 | 1 | 50 |
| 5 | 1 | 1 | 50 |
| 6 | 1 | 1 | 50 |
| 7 | 1 | 7 | 350 |
| 8 | 1 | 7 | 350 |
| 9 | 1 | 7 | 350 |
| 10 | 1 | 0 | 8650.75 |
| 11 | 1 | 0 | 8650.75 |
| 12 | 1 | 0 | 8650.75 |
+-----+----------+-----+---------+
谢谢!
答案 0 :(得分:3)
SELECT convertEntries.idx, convertEntries.capTable, convertEntries.cap,
default_caps.value
FROM convertEntries
LEFT JOIN default_caps
ON convertEntries.cap = default_caps.cap
AND convertEntries.capTable = default_caps.tab
答案 1 :(得分:1)
这是一个简单的连接,就像我看到的那样
From ConvertEntries e
Left Join default_caps c on e.tab=c.captable and e.cap=c.cap
我将其作为左连接进行,因为架构似乎可能存在数据问题。如果您在内部联接并且default_caps中不存在相应的查找,则将忽略该记录。
答案 2 :(得分:0)
我建议使用更有意义的列名,但是:
SELECT convertEntries.idx
, convertEntries.capTable
, convertEntries.cap
, default_caps.value
FROM convertEntries
INNER JOIN default_caps
ON default_caps.tab = convertEntries.capTable
AND default_caps.cap = convertEntries.cap
答案 3 :(得分:-1)
select
a.idx,
a.cap,
a.capTable,
b.Value
from convertEntries a
inner join default_caps b on a.tab = b.captable
and a.cap = b.cap