MySQL,根据列值从不同的行中选择

时间:2014-09-01 07:45:56

标签: php mysql sql

我有下表

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

链接字段存储ID,因此我可以设置两行之间的关系。

ID 01的链接字段设置为02.所以我希望ID 01使用在该字段中设置了ID的图像,所以它将是steve.jpg。

如何获取所有行,以便设置了链接字段的行以该图像结束?

3 个答案:

答案 0 :(得分:2)

您可以使用自联接来显示链接ID的图像名称

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

Demo

答案 1 :(得分:0)

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

答案 2 :(得分:-1)

这样的事情:

(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 )
)