我需要这样的查询:
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
答案 0 :(得分: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;
对于问题的第二部分,请查看使用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
);
然后,当用户登录时,使用函数CONNECTION_ID()
使用mysql连接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;
答案 1 :(得分: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'];