开发者

I need a logic to implement Mysql query

I have a 3 tables: 1. Users --开发者_StackOverflow中文版 here "userd id" is primary key 2. UserPermision --here "userd id" is a foreign key and there is "pageid" coloumn 3. Page -- here page id is a primary key

Now i need to write a query when i inser a new user say user id = "1" then this user id 1 should be inserted into Userpermision table and for this user it shouls have all the pages from page table .


I'm assuming you are using InnoDB.
In that case you have foreign key constraints and transactions.

If not you'll have to use triggers.

START TRANSACTION;

INSERT INTO users (name, etc) VALUES ('test', 'remainder');

SELECT last_insert_id() INTO @my_user_id;

INSERT INTO userpermission (userid, permission, pageid) 
  SELECT 
    @my_user_id as user_id
    , 'all' as permission
    , pageid 
  FROM pages 
  WHERE pages.userid = @my_user_id;

COMMIT;

This is assuming you've already made pages for that user.

link
http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html


You need two INSERT queries, one for each table.

INSERT INTO Users (user_id,...) VALUES (:user_id,...)

INSERT INTO UserPermission (user_id,page_id)
SELECT :user_id, page_id FROM Page

You can either execute them within the same transaction, or execute the second one from the AFTER INSERT trigger on the Users table.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜