如何将这个大查询转换为存储过程

时间:2014-02-19 11:19:04

标签: sql stored-procedures

如何将这个大查询转换为存储过程,我应该怎么做?有什么好处?

SELECT * 
FROM user_items
LEFT JOIN items ON (items.item_id = user_items.item_id) 
INNER JOIN item_categories ON (item_categories.item_id = items.item_id)
INNER JOIN item_subcategories ON (item_subcategories.item_id = items.item_id)
INNER JOIN brands ON (brands.brand_id = items.item_brand)
INNER JOIN item_photos ON (item_photos.item_id = items.item_id)

INNER JOIN place_items ON (place_items.item_id = items.item_id)
INNER JOIN places ON (places.place_id = place_items.place_id)

WHERE user_items.user_id = :user_id
    来自brands表的
  • 我只需要brand_name
  • 来自places表的
  • 我只需要place_name

我现在正在做的方式,我从brandsplaces得到所有列,所以我的一个朋友告诉我,我应该考虑使用存储过程

3 个答案:

答案 0 :(得分:2)

如果您只想要品牌和商品表中的列,则可以执行以下操作

"SELECT   brands.brand_name,places.place_name,
          user_items.*,items.*,item_categories .*,
          item_subcategories.*,item_photos.*,place_items.*
 FROM user_items
          LEFT JOIN items ON (items.item_id = user_items.item_id) 
          INNER JOIN item_categories ON (item_categories.item_id = items.item_id)
          INNER JOIN item_subcategories ON (item_subcategories.item_id = items.item_id)
          INNER JOIN brands ON (brands.brand_id = items.item_brand)
          INNER JOIN item_photos ON (item_photos.item_id = items.item_id)

          INNER JOIN place_items ON (place_items.item_id = items.item_id)
          INNER JOIN places ON (places.place_id = place_items.place_id)

          WHERE user_items.user_id = :user_id"

使用存储过程是重用一组SQL语句。存储过程的性能与它包含的SQL语句一样好。

更好的方法是提高代码的可读性,可以使用 ALIASES 来表名。

When to use SQL Table Alias

答案 1 :(得分:1)

根据我的经验,存储过程比它们值得更加麻烦,缺乏灵活性,因此比内联SQL更难维护,驻留在版本控制之外,并且如果有任何性能优势则无法提供很多。在这种情况下,存储的例程似乎没有必要或有益,因为您的查询不需要高级功能,例如光标。有关优缺点的另一个讨论,请参阅this post

答案 2 :(得分:0)

    DELIMITER $$
    DROP PROCEDURE IF EXISTS `ABC` $$
    CREATE PROCEDURE `ABC`(IN UID LONG)
    READS SQL DATA
    BEGIN
    SELECT * 
    FROM user_items
    LEFT JOIN items ON (items.item_id = user_items.item_id) 
    INNER JOIN item_categories ON (item_categories.item_id = items.item_id)
    INNER JOIN item_subcategories ON (item_subcategories.item_id = items.item_id)
    INNER JOIN brands ON (brands.brand_id = items.item_brand)
    INNER JOIN item_photos ON (item_photos.item_id = items.item_id)
    INNER JOIN place_items ON (place_items.item_id = items.item_id)
    INNER JOIN places ON (places.place_id = place_items.place_id)
    WHERE user_items.user_id = UID
    END $$
    DELIMITER ;



you can do like this and execute this and can call then :-

CALL ABC(1234);

where 1234 is user_id of user. Thank you