简体   繁体   English

在MySQL语句中使用函数而不是子选择

[英]Using a function within a MySQL statement instead of sub-selects

I have the function: 我有这个功能:

function get_kwp($siteid){

$this->db->select('siteid')
         ->from('nwsite')
         ->where('siteid', $siteid);
}

I now want to include this function within another MySQL statement to save having to do a sub-select every time i need to call it. 我现在想要在另一个MySQL语句中包含此函数,以节省每次需要调用它时必须进行子选择。

This is the other MySQL statement that i need it to be called into: 这是我需要调用的另一个MySQL语句:

$this->db->select("day, month, get_kwp($siteid) AS kwp")
         ->from('nwsite');

this doesn't seem to execute the function get_kwp(). 这似乎没有执行函数get_kwp()。

Any ideas? 有任何想法吗?

Thanks 谢谢

A simple Google on CodeIgniter subqueries returned the following result: http://codeigniter.com/wiki/Subqueries CodeIgniter子查询上的一个简单Google返回了以下结果: http//codeigniter.com/wiki/Subqueries

You cannot include a PHP function call in a SQL SELECT statement. 您不能在SQL SELECT语句中包含PHP函数调用。 You should build the subquery in your database statement. 您应该在数据库语句中构建子查询。 Use the link I gave to see how to actually do it. 使用我提供的链接来了解如何实际执行此操作。

EDIT 编辑

I just saw that the article references a library on GitHub, but the installation of this library is straightforward. 我刚刚看到文章引用了GitHub上的一个库,但是这个库的安装非常简单。

You can write a function in MySQL: 你可以在MySQL中编写一个函数:

DELIMITER $$

CREATE FUNCTION get_kwp(Mysite_id INTEGER) RETURNS INTEGER
BEGIN
  DECLARE result INTEGER;
  SELECT siteid INTO result FROM nwsite WHERE siteid = Mysite_id LIMIT 1;
  RETURN result;
END $$

DELIMITER ;

And use that in your query: 并在您的查询中使用它:

SELECT day, month, get_kwp('$siteid') AS kwp FROM nwsite;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM