一个新闻和新闻图片查询的问题
一个是新闻表一个是新闻图片表
现在想列出新闻和图片,如果一个新闻有多个图片,在查询的时候只显示出一个图片,这样的sql怎么写亚
我是这样写的
SELECT DISTINCTID ,n.*
p.ImageServerFile AS Expr1
FROM News n LEFT OUTER JOIN
pic p ON n.NewsID = p.NewsID
WHERE (n.Publish = 'one ') AND (n.NewscatalogID = 7 )
ORDER BY YEAR(n.NewsDate), MONTH(n.NewsDate), DAY(n.NewsDate) DESC
但是有错误,
我就是想如果新闻有图片我就在ImageServerFile这个字段上显示,如果没有就空,同时新闻id不重复,
------解决方案--------------------select m.* , n.图片字段 from 新闻表 m,
(
select a.* from 新闻图片表 a,
(select id , max(NewsDate) NewsDate from 新闻图片表 group by id) b
where a.id = b.id
) n
where m.id = n.id
------解决方案--------------------SELECT distinct, n.*
p.ImageServerFile AS Expr1
FROM News n
LEFT OUTER JOIN pic p ON n.NewsID = p.NewsID
WHERE (n.Publish = 'one ') AND (n.NewscatalogID = 7 )
ORDER BY n.NewsDate DESC
------解决方案--------------------SELECT DISTINCTID ,n.*
p.ImageServerFile AS Expr1
FROM News n LEFT OUTER JOIN
(select NewsID,max(ImageServerFile) ImageServerFile from pic group by NewsID) p ON n.NewsID = p.NewsID
WHERE (n.Publish = 'one ') AND (n.NewscatalogID = 7 )
ORDER BY YEAR(n.NewsDate), MONTH(n.NewsDate), DAY(n.NewsDate) DESC