我有一张映射表tableA
key value
-----------
1 "John"
2 "George"
3 "Kate"
4 "loves"
5 "hates"
和另一个包含基于tableB
tableA
col1 col2 col3
------------------
1 5 2
2 4 3
3 4 1
我想编写一个选择查询,它将返回table B
中的行,但会替换为相应的值。
e.g。输出必须是:
John | hates | George
George | loves | Kate
Kate | loves | John
谢谢。
答案 0 :(得分:2)
SELECT A1.value, A2.value, A3.value
FROM tableB
JOIN tableA as A1 ON tableB.col1 = A1.key
JOIN tableA as A2 ON tableB.col2 = A2.key
JOIN tableA as A3 ON tableB.col3 = A3.key;
答案 1 :(得分:1)
您应该将最后两项“爱”和“讨厌”放在一个单独的表中,因为它们代表的数据类型与其他3种不同。
以下是表格:
用户:
id name
----------
1 John
2 Edward
3 Kate
感受:
id type
----------
1 love
2 hate
feelings_users:
id user1_id feeling_id user2_id
-----------------------------------
1 1 2 2
2 2 1 3
3 3 1 1
这是查询:
select `Ua`.`name`, `F`.`type`, `Ub`.`name` from `feelings_users` as `X`
left join `users` as `Ua` on `X`.`user1_id` = `Ua`.`id`
left join `feelings` as `F` on `X`.`feeling_id` = `F`.`id`
left join `users` as `Ub` on `X`.`user2_id` = `Ub`.`id`
它将输出:
name type name
--------------------
John hate Edward
Edward love Kate
Kate love John