简体   繁体   中英

Make multiple queries in codeigniter and the results based in the first one

I want to display all rows of table article , and for each of article row i want get the SUM of votes from another table ( likes ), and this with one query.

Here what i have:

$query = "SELECT article.title,article.tags,article.description,article.slug,users.username,article.photo,article.id,article.date,SUM(likes.votes) as upvotes
          FROM article";
$query .= " LEFT JOIN users ON article.user_id = users.user_id ";
$query .= " LEFT JOIN likes ON likes.article_id = article.id ";

But my problem with this query, i get only one row ! because in table likes there only one row ...

I want to display results based on article table (i have about 50 rows in it)... and if there nothing related to votes for a specific article, we show (0 votes).

Thank you.

A stored function is a special kind stored program that returns a single value. You use stored functions to encapsulate common formulas or business rules that are reusable among SQL statements or stored programs.

Here you query should

$query = "SELECT article.title,article.tags,article.description,article.slug,users.username,article.photo,article.id,article.date,custom_SUM(article.id) as upvotes
          FROM article";
$query .= " LEFT JOIN users ON article.user_id = users.user_id ";

and custom mysql function

DELIMITER $$
    CREATE FUNCTION custom_SUM(p_article_id int(11)) RETURNS VARCHAR(10)
        DETERMINISTIC
    BEGIN
        DECLARE likes varchar(10);
      SET likes =(select sum(likes.votes) from likes where likes.article_id=p_article_id);

     RETURN (likes);
    END

refer link here http://www.mysqltutorial.org/mysql-stored-function/

Add group by to the code :

$query = "SELECT article.title, article.tags, article.description, article.slug, users.username, article.photo, article.id, article.date, SUM(likes.votes) as upvotes FROM article";
$query .= " LEFT JOIN users ON article.user_id = users.user_id ";
$query .= " LEFT JOIN likes ON likes.article_id = article.id ";
$query .= " GROUP BY article.id";

Or use codeigniter method:

$this->db->select("article.title, article.tags, article.description, article.slug, users.username, article.photo, article.id, article.date");
$this->db->select("SUM(likes.votes) as upvotes", false);
$this->db->from("article");
$this->db->join("users","article.user_id = users.user_id");
$this->db->join("likes","likes.article_id = article.id");
$this->db->group_by("article.id");
$query = $this->db->get();
return $query->result_array();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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