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'
精彩评论