简体   繁体   English

MySQL,根据列值从其他行中选择

[英]MySQL, selecting from a different row based on column value

I have the following table 我有下表

---------------------------
|ID  |Image      | link    |
|01  |           | 02      |  
|02  |steve.jpg  |         |         
|03  |eric.jpg   |         |         
----------------------------

The link field stores IDs, so I can set a relationship between two rows. 链接字段存储ID,因此我可以设置两行之间的关系。

The ID 01 has its link field set to 02. So I want ID 01 to use the image whose ID is set in that field, so it'll be steve.jpg. ID 01的链接字段设置为02。因此,我希望ID 01使用该字段中设置了ID的图像,因此它将为steve.jpg。

How can I get all rows, so that the ones with the link field set end up with that Image? 如何获取所有行,以使带有链接字段的行以该图像结尾?

You can use self join in order to show the image name for link id 您可以使用自我连接以显示链接ID的图像名称

select t.*,t1.Image as link_image
from t 
left join t t1 on(t.link = t1.ID)

Demo 演示

SELECT a.id, b.image, a.link
FROM YourTable AS a
JOIN YourTable AS b ON a.link = b.id
UNION
SELECT id, image, link
FROM YourTable
WHERE link IS NULL

Something like this: 像这样:

(SELECT ID, Image from mytable WHERE link = '' )
UNION ALL
(SELECT m1.ID as ID, m2.Image as Image 
   FROM mytable AS m1 INNER JOIN mytable AS m2 ON ( m1.link=m2.ID )
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM