日期:2014-05-16  浏览次数:21023 次

两表关联查询,怎么写哦?
news表存着一些商家动态信息(新闻活动信息) 
base表为商家的基本信息(名称、类型等等)

news 字段

id title indexuid ..

base 字段
id type indexuid .. 

这两表中indexuid 是互通的 


现在就是要在news表中查询20条记录,但是商家类型为指定的,但是news表并没有这样的字段记录商家类型,必须联动base表查询

我是这样的写的:

select top 20 * from news where ck=1 as a where id=(select max(id) from base as b where b.indexuid=a.indexuid and b.type=10)

这样写提示报错了 在as a 附近

求高手指点一下


------解决方案--------------------
按你的方式:

select top 20 * from news as a where ck=1 where id=(select max(id) from base as b where b.indexuid=a.indexuid and b.type=10)


更好的方式是使用join,不过我看到你的代码有点疑惑,news.id与base.id是多对一?
indexuid是一对一?
------解决方案--------------------
活动新闻和商家信息是多对一的话用外连接?一对一的话内连接
try:

SELECT TOP 20 a.* 
FROM news AS a 
LEFT OUTER JOIN base AS b
ON b.indexuid=a.indexuid

where a.ck=1 AND b.type=10