2

我需要这样的查询:

SELECT * FROM table WHERE owner_field = 100

但是“owner_field”在几个表中是不同的。我想使用索引来识别字段:

SELECT * FROM table WHERE (SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.STATISTICS WHERE TABLE_NAME=table AND INDEX_NAME='owner') = 100

我究竟做错了什么?

更新:我想将此条件添加到 INSERT、UPDATE、DELETE 查询以进行安全控制(用户只能使用自己的数据执行任何操作)。

Mysql结构如下:

user_id     
post_id        post_author    = user_id
category_id    category_owner = user_id
4

2 回答 2

0

我想我找到了一个更简单的方法:

CREATE VIEW indexed_posts AS 
SELECT * FROM posts, users
WHERE post_author = user_id 
WITH CHECK OPTION;

然后我可以使用查询:

SELECT * FROM indexed_posts WHERE user_id = $_SESSION['user_id'];
于 2012-10-29T07:50:16.830 回答
0

这是一个糟糕的设计,而且很可能是不可能的。

为什么不使用VIEW?

CREATE VIEW table1_ownerfield AS SELECT ownerfield_1 FROM table1;
CREATE VIEW table2_ownerfield AS SELECT ownerfield_2 FROM table2;

然后将它们用作表格:

SELECT * FROM table1_ownerfield;
SELECT * FROM table2_ownerfield;

对于您问题的第二部分,请查看 using triggers

编辑:

听起来您想要的视图类似于:

CREATE VIEW my_posts AS 
    SELECT * FROM posts WHERE post_owner = CURRENT_USER() 
    WITH CHECK OPTION;
CREATE VIEW my_categories AS 
    SELECT * FROM categories WHERE category_owner = CURRENT_USER() 
    WITH CHECK OPTION;

你可能想做这样的事情:

创建表:

 CREATE TABLE user_connections (
     user_connection_id INT AUTO_INCREMENT PRIMARY KEY,
     mysql_connection_id INT,
     user_id INT
 );

然后当用户登录时,使用函数 mysql 连接 ID 填充此表CONNECTION_ID()

然后您可以创建如下视图:

CREATE VIEW my_posts AS 
    SELECT * FROM posts p JOIN user_connections uc 
    WHERE uc.mysql_connection_id = CONNECTION_ID() 
    AND p.post_user_id = uc.user_id 
    WITH CHECK OPTION;
CREATE VIEW my_categories AS 
    SELECT * FROM categories c JOIN user_connections uc 
    WHERE uc.mysql_connection_id = CONNECTION_ID() 
    AND c.category_user_id = uc.user_id 
    WITH CHECK OPTION;
于 2012-10-28T19:12:37.863 回答