外星屠异:select语句使用两个表格时出现重复???

来源:百度文库 编辑:杭州交通信息网 时间:2024/04/28 05:34:41
select book.bookname,shoppingcarts.BookQuantity from book,shoppingcarts where book.bookid in (select bookid from shoppingcarts where cartidstring='lipeng-27')

谁知道这是怎么回事呀?
如果这样写就是两条记录:
select bookname from book where bookid in (select bookid from shoppingcarts where cartidstring='lipeng-27')

select ...from 两个表,这是连接查询,而你没有设置连接条件,所以实际上结果集是笛卡尔积形式,出现重复那是自然的。
比如 第一个表中某个字段有2条
a
b
另外一个的数据是
c
d
不加条件,直接from两个表的话
结果就是
a,c
b,c
a,d
b,d

如果不想出现重复,你必须在where 子句里将book表和shoppingcarts表可以关联的字段写出来

假设book表中bookid字段与shoppingcarts表中bookid字段时对应的,那么
语句如下:

select book.bookname,shoppingcarts.BookQuantity
from book,shoppingcarts
where book.bookid =shoppingcarts.bookid and shoppingcarts.cartidstring='lipeng-27'

另外,如果shoppingcarts 表中有重复的行,按上边的写法还是会出现重复的。这要根据你的实际表结构和要求来改善了。

有问题
book和shoppingcarts的连接条件没写明
改为:
select book.bookname,shoppingcarts.BookQuantity from book,shoppingcarts where book.书名=shoppingcarts.书名 book.bookid in (select bookid from shoppingcarts where cartidstring='lipeng-27')
试试行不?