1

我有一个映射表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但替换为它们的适当值。

例如输出必须是:

John   | hates | George
George | loves | Kate
Kate   | loves | John

谢谢你。

4

2 回答 2

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;
于 2013-01-30T16:38:19.327 回答
1

您可能应该将最后 2 项“loves”和“hates”放入单独的表中,因为它们代表的数据类型与其他 3 项不同。

以下是表格:

用户:

id  name
----------
 1  John
 2  Edward
 3  Kate

情怀:

id  type
----------
 1  love
 2  hate

感受_用户:

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
于 2013-01-30T17:01:05.880 回答