开发者

Combine results from two tables into one recordset

I have two tables items and content.

 items:|ID|menu|img

table

 itemcontent |ID|parent|title|content

content holds is paired to items by parent holding the title and content

i want to search all the items and also print out those records wich do not have a title present in the itemcontent table whereby the titles will be printed as "Empty". so printing out the output would look something like:

title: test1 and ID: items.ID=1
title: Empty and ID: items.ID=2
title: Empty and ID: items.ID=3
title: test2 and ID: items.ID=4
title: Empty and ID: items.ID=5
etc...

I tried the following and then some but to no avail:

SELEC开发者_运维技巧T items.*, itemcontent.title, itemcontent.content
FROM items, itemcontent
WHERE itemcontent.title LIKE '%$search%'
     AND itemcontent.parent = items.ID 
order by title ASC          

A little help would be much appreciated


Since you want all the rows from items whether or not they have a match in itemcontent, plus a field from itemcontent when there is a match you need to use an OUTER JOIN:

SELECT items.*, COALESCE(itemcontent.title, 'empty'), itemcontent.content
FROM items LEFT OUTER JOIN itemcontent ON itemcontent.parent = items.ID 
 WHERE (itemcontent.title LIKE '%$search%' OR itemcontent.title IS NULL)
 ORDER BY items.ID, itemcontent.title ASC    

There are small differences among SQL dialects (for instance, not all versions have COALESCE) so if you want a more precise answer indicate which product you're using.


Just to be sure you might want to ORDER BY itemcontent.title and not just title or select itemcontent.title AS title? Do you have a field called title in the items table?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜