Mysql使用列表查询的问题
发布于 8 年前 作者 lishinko 3970 次浏览 来自 问答

我现在有这样的一个表: 玩家id : number, 区id : number, 名字 : string, 其中,(玩家id, 区id)是唯一的,但是单独的 玩家id 或 区id 都不是唯一的。 现在,想获得玩家的名称列表: 我想写出类似于:

select * from table where (玩家id, 区id) in ({1,1}, {1,2}, {3,3});

也就是查询 玩家id, 区id成对匹配列表{1,1}, {1,2}, {3,3}的玩家列表。,但是我搜索了下,没有发现相应的sql语法。 请问这类功能应该怎么实现呢? 我用的是 MySql数据库, node-mysql做连接

13 回复

没懂你究竟要什么,上面说是 想获得玩家的名称列表,后面又说是也就是查询 玩家id, 区id成对匹配对应列表的玩家 。select * from table where 玩家id=xxx and 区id=xxx。这样吗?

@imhered 就是这样的,只是我想一条sql语句查询多个玩家的名字。 select * from table where 玩家id=1 and 区id=1 select * from table where 玩家id=1 and 区id=2 select * from table where 玩家id=3 and 区id=3 这么3条语句可不可以合并成一条呢? 如果这样不行,那么batch操作也是可以的。问题还是我不熟悉语法:(

@lishinko select * from table where 玩家id in(你要查的玩家id) and 区id in(你要查的区id)

@lishinko select * from table where 玩家id in(1,2,3) and 区id in(1,2,3) 这里面还要看你的数据是存在一张表里还是多张表里,如果是多张表的话 还要找唯一限制条件。

@imhered 谢谢,我是新手(数据库的新手…同时还没有测试你发给我的这个sql),但是我想问下: select * from table where 玩家id in(你要查的玩家id) and 区id in(你要查的区id) 不应该是“查询 玩家id范围 与 区id范围 的笛卡尔积”吗? 就是说,对于数据 玩家id 区id 名称 1, 1, "asdf11" 1, 2, "asdf12" 2, 1, "asdf21" 2, 2, "asdf22" select * from table where 玩家id in(1,2) and 区id in(1,2) 不是会返回全部数据吗? 如果我想返回 1, 1, "asdf11" 1, 2, "asdf12" 2, 1, "asdf21" 这样的呢?

@lishinko 对没错,是这个两个的笛卡尔积。

@imhered 谢谢,数据实际上是放在多个表里面的(一个区一个表,所以实际的sql不难写)。我只是想问下在一个表的话应该怎么做,趁机学习下MySql…

@lishinko 可以用distinct关键字过滤掉重复的用户名

@imhered 好的。我学习下distinct关键字的用法。 另外,我修改了2楼的内容,请问2楼的问题有没有什么办法呢?

@lishinko 3个table是一张表还是3张不同的表

@imhered 3个table是同一张表

@lishinko select * from table where 玩家id in(1,2,3) and 区id in(1,2,3) 这只是一种写法,实现方法有很多种,自己狗一下sql语法吧。

@imhered 好吧我再查一下吧。

回到顶部