我很抱歉,但我不知道如何用正确的词语指明我的问题(这就是为什么我不知道要放入谷歌或查询mysql-doc的原因)。我试着在这里简化和描述我的问题。我想解决方案很简单,但我找不到它。
我有两张桌子。第一个只包含一些人。
| id | name | lastname | age | size |
| 1 | 'max' | 'foo' | 12 | 156 |
| 2 | 'john' | 'bar' | 20 | 191 |
| 3 | 'jane' | 'doe' | 17 | 175 |
第二个描述了谁给了谁礼物。 (这个例子只是出于我的想法而明确,我的问题是什么)
| id | gift_description | from_kid | to_kid | price |
| 1 | 'bow and arrow' | 2 | 1 | 40$ |
| 2 | 'rc car' | 3 | 2 | 20$ |
| 3 | 'baby doll' | 1 | 3 | 5$ |
现在我正在寻找一个SELECT-Statement,它给了我孩子们的名字:
| id | kid_a | kid_b | gift_description |
| 1 | john | max | 'bow and arrow' |
| 2 | jane | john | 'rc car' |
| 3 | max | jane | 'baby_doll' |
我尝试过类似的事情:
SELECT id, gift_description, name AS kid_a, name AS kid_b
FROM TABLE gifts, persons
WHERE (gifts.from_kid = persons.name
AND gifts.to_kid = persons.name);
当然这不行,但我错过了最后一块。 (你可以很容易地看到,我对MYSQL不太满意。)
答案 0 :(得分:4)
您通过连接执行此操作,实际上是两个连接:
select t2.id, tfrom.name as kid_a, tto.name as kid_b, t2.gift_description
from secondtable t2 join
firsttable tfrom
on t2.`from` = t1.id join
firsttable tto
on t2.`to` = t2.id;
答案 1 :(得分:1)
这应该这样做,你要找的是JOIN
陈述
SELECT G.id, p.name AS kid_a, P1.name AS kid_b, gift_description
FROM persons P
INNER JOIN gifts G ON G.from_kid = P.ID
INNER JOIN persons P1 ON P1.ID = G.to_kid