Mysql多条件批量查询

请教一个问题:mysql中,我查询语句
select * from tableA where name='test' and age='18';
然后我有一个name和age的list列表,分别通过这两个条件去查询,有什么比较方法可以查询;

eg:
select * from tableA where name='test' and age='18';
select * from tableA where name='test1' and age='18';
select * from tableA where name='test2' and age='20';
select * from tableA where name='test2' and age='56';
···

其中查出来的数据对应Java的一个实体。其中List表的大小为500-3000,数据表的记录为每天8万左右

阅读 23.1k
7 个回答

建立视图查询,这样效率会好点。至少比临时表效率稍快

小数据建议拼接Sql:

WHERE (  ( x = ? AND y = ? AND z = ? )
      OR ( x = ? AND y = ? AND z = ? )
      ... 
      OR ( x = ? AND y = ? AND z = ? )
      )

大数据建议使用虚拟表:

CREATE (TEMPORARY) TABLE tmp_table ...;

INSERT INTO tmp_table (x,y,z)
VALUES (?,?,?), (?,?,?), ... ;

SELECT t.*
FROM my_table AS t
JOIN tmp_table AS tmp
ON  ( t.x = tmp.x AND t.y = tmp.y AND t.z = tmp.z );

不建议使用(对索引不友好):

WHERE (x,y,z) IN ((?,?,?), (?,?,?), ...)

table A 添加一列名称nameage 里面的值是 name和age的值合并 例如 test18
select * from tableA where nameage in ('test18','xxxxxx','xxxxxxx')

当然你不添加列也行,自己sql拼下也行

新手上路,请多包涵

togeek的答案很帅
sql的效率可能要再考虑下

数据量不大的时候,可以这样干。

SELECT * FROM tableA
WHERE (name, age) IN (
('test', 18),
('test1', 18),
('test2', 20),
('test2', 56))

但通过explain以上查询会发现,这种写法是没法用上索引的,所以查询效率很低。

select a.* 
from tableA a
inner join list l on l.name=a.name and l.age=a.age

不行吗?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题