如何构建左连接以生成此输出?
表1:主表
| ID | Team | Color |
| 1 | A | Red |
| 2 | A | Blue |
| 3 | B | Green |
| 4 | B | Green |
| 5 | C | Yellow |
表2:查找表
| Team | Color | Final |
| A | Red | A-1 |
| A | Blue | A |
| B | Green | B |
| C | Yellow | C |
输出表
| ID | Team | Color | Final |
| 1 | A | Red | A-1 |
| 2 | A | Blue | A |
| 3 | B | Green | B |
| 4 | B | Green | B |
| 5 | C | Yellow | C |
在excel中,逻辑将是这样的......
=IF(AND(Team = "A", Color = "Red"),"A-1", Team = Team))
如何使用内连接转换为访问或mysql中的sql查询?我有类似的东西,但不知道如何在查询中构造if语句。
我希望查询检查团队 =' A' AND 颜色 ='红色'然后返回' A-1'否则返回相同的Team列值。
SELECT Table1.ID, Table1.Team, Table1.Color, Table2.Final FROM Table1
INNER JOIN Table2 ON Table1.Team = Table2.Team;
任何帮助都会受到高度赞赏。非常感谢。
答案 0 :(得分:2)
您可以在JOIN子句中使用AND关键字:
SELECT * FROM Table1
INNER JOIN Table2
ON Table1.Team = Table2.Team AND Table1.Color = Table2.Color
答案 1 :(得分:0)
尝试这个未经测试的查询:
SELECT Table1.ID, Table1.Team, Table1.Color,
case Table1.Team when "A" then
case Table1.Color when "READ" then
Table2.Final
else
Table1.Team
end
else
Table1.Team
end
Table2.Final FROM Table1
FROM Table1
INNER JOIN Table2 ON Table1.Team = Table2.Team;
答案 2 :(得分:0)
试试这个
SELECT A.ID, A.Team, B.Color, B.Final
FROM MainTable as A
LEFT JOIN LookupTable as B
ON A.team = B.team
AND B.Final = CASE COLOR WHEN "RED" THEN "A-1" ELSE B.Final END
答案 3 :(得分:0)
我试过这个并得到了你期望的输出。
SELECT
t1.id,
t1.team,
t1.color,
t2.final
FROM
table1 AS t1 LEFT JOIN table2 AS t2
ON t1.Team = t2.Team AND t1.Color = t2.Color