duandui5648 2016-05-23 10:11
浏览 49
已采纳

如何从同一个表中获取相关行?

I have a table like this:

// mytable
+----+---------+---------+
| id | related |  color  |
+----+---------+---------+
| 1  | 1       | red     |
| 2  | 1       | blue    |
| 3  | 3       | green   |
| 4  | 1       | white   |
| 5  | 3       | brown   |
| 6  | 6       | gray    |
| 7  | 3       | black   |
| 8  | 1       | orange  |
| 9  | 6       | pink    |
+----+---------+---------+

I have an id number and I need to get the color of related id.

For example:

$id = 4; // I need to get `red`
$id = 5; // I need to get `green`
$id = 6; // I need to get `gray`
$id = 9; // I need to get `gray`

I can do that by using a JOIN. Something like this:

SELECT t2.color FROM mytable t1 JOIN mytable t2 ON t1.related = t2.id WHERE t1.id = :id

My query works as expected .. But I'm not sure using a JOIN for doing that is standard. Actually I'm trying to know is there any better approach? Or mine is a normal way?

  • 写回答

3条回答 默认 最新

  • dongzhi1851 2016-05-23 10:19
    关注

    What's wrong with SELECT t.related FROM mytable t WHERE t.id = :id? JOIN makes nothing more but checking if there is a actual id in 'related' column or not

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog