读书人

两表关联查询如何写哦

发布时间: 2013-09-05 16:02:06 作者: rapoo

两表关联查询,怎么写哦?
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

读书人网 >ASP

热点推荐