开发者

Calling stored procedure using value from second stored procedure to produce single result?

I have decided to educate myself on stored procedures in MySQL, but with the syntax being quite different from my usual stomping ground (php/javascript), I was hoping to determine if my understanding of the capabilities of these procedures is correct, and if so, how I achieve what I a开发者_StackOverflow中文版m after.

Currently, I am have two tables, 'people' and 'posts', as follows:

people
person_id INT(10)
first_name VARCHAR(32)
last_name VARCHAR(64)

posts
post_id INT(10)
author_id INT(10)
body_text TEXT
created DATETIME

From that, I created a simple all-purpose stored procedure, as follows:

DELIMITER //
CREATE PROCEDURE getPerson(IN person INT(10))
  BEGIN
    SELECT CONCAT(first_name, ' ', last_name) as long_name, CONCAT(last_name, ', ', first_name) as index_name FROM people WHERE person_id = person;
  END //
DELIMITER ;

So far so good, but now here's where my understanding breaks down... I want to create a second procedure called 'getPost', which when passed a post_id, will return the post data from the respective row in the posts table, but also call the getPerson procedure on the author_id column, so that a single result returned will consist of the fields: post_id, long_name, index_name, body_text, created.

I've trial and errored for a couple of hours, and while I may have had the right approach at one point (use a join on the result of getPerson?), my sql syntax hasn't extended much beyond single-statment MySQL calls from PHP. My questions are:

  1. Is this a common/reasonable approach to what I want to do or is there something better? (I don't want to use a scripting language)
  2. If so, might someone share how to do this?
  3. Am I correct to use a procedure for this kind of thing, or is a function as good/better?

Thanks for any help!


Why don't you just create a view called viewPeoplePosts that combines People and their Posts. Then you can modify your stored proc to query the view. Let the view do all the hard work and let stored procedure simply return the result.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜