+ -
当前位置:首页 → 问答吧 → SQL查询并输出问题

SQL查询并输出问题

时间:2011-11-20

来源:互联网

表结构数据:
shop表 
字段
shopid title img
1 标题 1.jpg
2 标题 2.jpg
3 标题 3.jpg

url表 
字段
id name shopid
1 a 1
2 b 0
3 c 0

请问怎么查询当url表内shopid有与shop表shopid等同的时候输出url表name如果没等同输出shop表shopid

输出结果是循环的

作者: jhtongnet   发布时间: 2011-11-20

VBScript code
<%
Set conn = CreateObject("ADODB.Connection")
conn.Open "xxxxxx"

sql = "SELECT a.shopid, b.name FROM shop a LEFT JOIN url b ON a.shopid=b.shopid"
Set rs = CreateObject("ADODB.RecordSet")
rs.CursorLocation = 3
rs.Open sql, conn, 1, 1
Set .AcriveConnection = Nothing
Do While Not rs.EOF
  If IsNull(rs("name").value) Then
     Response.Write rs("shopid").value & "<br>"
  Else
     Response.Write rs("name").value & "<br>"
  End If
  rs.MoveNext
Loop
rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing
%>

作者: hookee   发布时间: 2011-11-20


SQL code

--构造示例数据
declare @shopid table(
shopid int,
title nvarchar(10),
img nvarchar(10)
)

declare @url table(
id int,
name nvarchar(10),
shopid int
)

insert into @shopid values
(1,'标题','1.jpg'),
(2,'标题','2.jpg'),
(3,'标题','3.jpg')


insert into @url values
(1,'a',1),
(2,'b',0),
(3,'c',0)


-- select * from @shopid

/*
  执行查询
  
  */
  
  select name as result from @url u,@shopid s where u.shopid = s.shopid

  select s.shopid as result from @shopid s where s.shopid not in (select u.shopid from @url u)

作者: p2227   发布时间: 2011-11-20