开发者

Adding where clause to MySQL session

Is there a manner to add something like a where clause as a 'global' parameter for a mysql session.

For example 开发者_开发问答an company has multiple user and you want to query for the user in this company, normally you would use a statement like:

SELECT * FROM users WHERE users.companyId = 2;

The issue is that adding the WHERE clauses would mean a huge impact on the code. Though, we defined the relations and thus I image (though, I don't think it exists), that you could create a session with the "global" constrained that all queries in that session should comply to.


You can create a view

CREATE VIEW view2 AS SELECT * FROM table1 WHERE companyid = 2;

If slowness is your curse, there are a few things you can do:

  • put an index on the where field(s) in this case companyid.
  • if you need more speed you can partition the table by companyid.
  • make the table a memory table, and use hash indexes for = and IN fields.
  • use InnoDB, instead of MyISAM. InnoDB has faster indexes.
  • Do not use select *, explicitly select only the fields you need.

See: http://dev.mysql.com/doc/refman/5.0/en/create-view.html
http://dev.mysql.com/doc/refman/5.5/en/index-btree-hash.html
http://dev.mysql.com/doc/refman/5.0/en/memory-storage-engine.html
http://dev.mysql.com/doc/refman/5.1/en/partitioning.html


The answer is NO.

As said before, you should put an index on that coloumn. And you can create a view.

Also you could use a temporary table.

From mysql docs:

You can use the TEMPORARY keyword when creating a table. A TEMPORARY table is visible only to the current connection, and is dropped automatically when the connection is closed. This means that two different connections can use the same temporary table name without conflicting with each other or with an existing non-TEMPORARY table of the same name. (The existing table is hidden until the temporary table is dropped.)

As a final thought, I can say that if you're performing the same query over and over again, you should rethink your model diagram, maybe do some denormalization.


What will happen when you perform select from table that has no companyId :) You can create views however, and select from them instead

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜