英文:
How to compare two columns from results of another query?
问题
当我在destination列中搜索“Queenstown”时,我想获得以下结果:
| id | sequence | destination |
|---|---|---|
| 3 | 2 | 东伦敦 |
| 3 | 3 | 格伯哈 |
英文:
Table:
| id | sequence | destination |
|---|---|---|
| 2 | 1 | Johannesburg |
| 2 | 2 | Durban |
| 2 | 3 | Cape Town |
| 3 | 1 | Queenstown |
| 3 | 2 | East London |
| 3 | 3 | Gqeberha |
When I search for "Queenstown" in the destination column I would like to get:
| id | sequence | destination |
|---|---|---|
| 3 | 2 | East London |
| 3 | 3 | Gqeberha |
I want records where sequence is greater than that of the queried record of which id is the same.
答案1
得分: 1
使用自连接:
SELECT t1.*
FROM yourTable AS t1
JOIN yourTable AS t2 ON t1.id = t2.id AND t1.sequence > t2.sequence
WHERE t2.destination = 'Queenstown'
ORDER BY t1.sequence
t1.id = t2.id 使 id 相同,t1.sequence > t2.sequence 使序列高于当前记录。
英文:
Use a self-join:
SELECT t1.*
FROM yourTable AS t1
JOIN yourTable AS t2 ON t1.id = t2.id AND t1.sequence > t2.sequence
WHERE t2.destination = 'Queenstown'
ORDER BY t1.sequence
t1.id = t2.id makes the id the same, and t1.sequence > t2.sequence makes the sequence higher than the current record.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论