开发者

Pull column twice from same table without subquery

I use the following query (in a PHP script)

SELECT *,
(SELECT head FROM pages WHERE id='0') AS nullhead
FROM pages WHERE id='$id1' OR id='$id2'

It pulls out data for a given page, including the value of the head column. However, the head column may be NULL, in which case the value for which id=0 is used instead.

Is it possible to do this without the sub开发者_Python百科query on line 2, while still using only one query?


You want to do a self-join here (in this case, a cartesian self-join)

select a.*, b.head as nullhead
from pages a, pages b
where a.id in ( '$id1', '$id2' )
and b.id = '0'


If you want to select 0 when head is NULL use COALESCE

SELECT *, COALESCE(head, 0)
FROM pages WHERE id='$id1' OR id='$id2'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜