MySQL Stored functions and php - php

So i have this query to fetch all posts
select id, title
from posts
where type = 'article'
and i have a stored function that calculate the total of views and return the result
i know i can execute it like
select totalView(id)
but how can i merge the two queries to return all posts with the total view of each post
maybe something like
select id, title, totalView(id) as total
from posts
where type = 'article'
Thank you.

select count(*) as total, id, title from posts where type = 'article'
EDIT : It will count all the rows of $id
select count(*) as total, id, title from posts where type = 'article' AND id = $id;

Related

laravel get data when give id not match with join table id

here is my category table data
id
1
2
6
7
when in my post bale I join with this category table
here is my post table sample data
ID = 1,
name = 'hellow'
category id = 4 (i join with category table but selected category is
deleted)
here is my index SQL query (when categy_id match with the category.id) then only its fetch
$post = DB::table('posts)->join('category','posts.category_id','categories.id')-.paginate(10);
for some reason, the selected category can be deleted so I try to get category deleted post data
here is my query
$cpost = DB::table('posts')->join('categories','posts.category_id', '!=' ,'categories.id')->select('post.*')->paginate(5);
but above query duplicate post data based on available category data
i want all post data which are category id is not matched with in category table id how can i get that ?
Try this. Key is the leftJoin instead of default innerJoin (join).
// posts without assigned or existing category
$posts = \DB::table('posts')
->leftJoin('category','posts.category_id','categories.id')
->whereNull('categories.id')
->paginate(10);
why are you doing a join for this? you already have category id stored in your post table.
$cpost = DB::table('posts')->where('category_id','!=', $category_id)->paginate(5);
Just try it:
$cpost = DB::table('posts')
->join('categories','posts.category_id', '=' ,'categories.id')
->select('post.*', 'categories.*')
->whereNotIn('posts.category_id', DB::raw('select id from categories'))
->paginate(5);

Mysql on select update records selected

I have mysql table posts
Posts
PostId (int)
PostTitle (varchar)
PostContent (text)
PostHits (int)
PostStatus (varchar)
and I read these records on select query like
SELECT * FROM posts WHERE PostStatus LIKE 'ALIVE';
is it possible that all records increment their value of PostHits on each select if they qualify where clause? if yes what is the best possible way, currently I am doing it using two queries select and then update based on where id in(all selected posts ids). I am looking for single query solution.
Is this what you need?
UPDATE posts
SET PostHits = PostHits + 1
WHERE PostStatus LIKE 'ALIVE'
Using SELECT only
SELECT
PostId,
PostTitle,
PostContent,
PostHits + 1 AS PostHits,
PostStatus
FROM posts
WHERE PostStatus LIKE 'ALIVE'

How do I select the top three rows in my database for posts

I have created a posting system along with a liking system. I wanted to select the top three posts with the most likes but I don't know how to do that.
I have this code but I can't figure out how to select more than just one row.
$get_pop_posts = mysql_query( "SELECT MAX( likes ) AS popular_posts FROM `posts`;" );
while($fetch_pop_posts = mysql_fetch_array($get_pop_posts)){
$pop_posts = $fetch_pop_posts['popular_posts'];
echo $pop_posts;
}
this piece of code only fetches one row from the database.
SELECT *
FROM posts
order by likes desc
limit 3
SELECT MAX( likes ) AS popular_posts FROM posts
This query return single result because of the function MAX().
Try this
SELECT TOP 3 FROM posts
Firstly give unique id to each post that should be incremented automatically each time a new post comes.
Then,
SELECT id FROM posts order by likes desc limit 3
Pass these id's as arrays to get the complete post.

Count how many of each value from a field with MySQL and PHP

I've seen that question several times but I can't find out how to display the result. I have a movie database and I would like the count of each genre of movie in my top menu in a single MySQL query so my menu would display like this:
Total Movies (300)
Drama (50)
Comedy (75)
Thriller (30)
...and so on...
I've found some MySQL query on this site but no one specify HOW to handle the counts after the SQL query. Something like this would probably work:
select genre, count(*) from movies group by genre
But how do I display the count for each value afterwards?
Thank you very much!
Alias the count part so you have an easily accessible column name:
SELECT genre, count(*) AS nb_movies FROM movies GROUP BY genre
then you can access it like $row['nb_movies'].
Without the alias the aggregate column takes the name of the aggregate function call which produced it, so in your case it would be accessed like $row['count(*)'].
Try
select genre, count(*) AS total from movies group by genre
Use total as your count for eg.
echo $result['total'];
Try this,
SELECT genre, count(*) AS total_genre_movies FROM movies GROUP BY genre
Now you can access like $result['total_genre_movies']
It's easier if you alias the result of count(*)
select genre,
count(*) as total
from movies
group by genre
Then you can access it as $row['total'] when you fetch the result into $row in exactly the same way you'd reference $row['genre']
select genre, count(*) as genre_count from movies group by genre
Now you can access like $result['genre_count']
Try this,
$result = mysql_query("select genre, count(*) as genre_count from movies group by genre");
while($row = mysql_fetch_array($result)) {
$genre = $row['genre'];
$genre_count = $row['genre_count'];
}

How to select a column value as a column name and group the results as a row

How do I select a column value as a column name and group the results as a row.
I have a table as such:
id articleId label value
1 1 title Example title
2 1 description This is the description
3 1 author Me
4 2 title Example of another type of article
5 2 description Short description
6 2 author Someone else
Is it possible to select all of the rows and use the label as the column name and the value as the value of that column name and then group them by the article name.
So how I would like to have it returned:
articleId title description author
1 Example title This is the.. Me
2 Example of an.. Short descr.. Someone else
I'm using this for a CMS where the user can define the fields for an article so we don't have to customize the table's. This is why i'm not making the tables as the I would like to have it returned. I am also aware that I can just as easily convert the result to this in php.
-- edit --
Can this be done without knowing what labels are added? In this example im using title, description and author. But it could very well be something totally different like title, shortDescription, availableTo, techInformation, etc.. The idea is that the article's are customizable for the user without needing to change the database and query's
I figured I'd better post as an answer, even if not what OP would like to hear. What you are asking to do is to populate a query with a variable number of columns based on the distinct values within column label, all associated with articleID. Taking your specific example, the following would be the resultant query that I would most likely go to in this instance (though the example from #Devart is equally valid)
SELECT
t.id,
t.articleId,
t1.value AS title,
t2.value AS description,
t3.value AS author
FROM `tableName` t
LEFT JOIN `tablename` t1
ON t1.article_id = t.article_id AND t1.label = 'title'
LEFT JOIN `tablename` t2
ON t2.article_id = t.article_id AND t2.label = 'description'
LEFT JOIN `tablename` t3
ON t3.article_id = t.article_id AND t3.label = 'author'
Now expanding this to account for up to n labels, we get the following query (metacode included, this query will NOT execute verbatim)
SELECT DISTINCT label FROM `tableName`;
SELECT
t.id,
t.articleId
// for (i=1;i<= number of distinct labels) {
,t[i].value AS [value[i]]
// }
FROM `tableName` t
// for (i=1;i<= number of distinct labels) {
LEFT JOIN `tablename` t[i]
ON t[i].article_id = t.article_id AND t[i].label = [value[i]]
// }
;
So what you can do is one of the following.
SELECT t.* FROM tablename t and then have PHP process it as required
SELECT DISTINCT label FROM tablename and have PHP build the second query with the many LEFT JOINs (or MAX / GROUP BY logic if preferred)
Create a Stored Procedure to do the same as #2. This would most likely be more efficient than #2 however may be less efficient overall than #1.
You can use pivote table trick -
SELECT
articleId,
MAX(IF(label = 'title', value, NULL)) AS title,
MAX(IF(label = 'description', value, NULL)) AS description,
MAX(IF(label = 'author', value, NULL)) AS author
FROM
table
GROUP BY
articleId
Try below :
select t1.articleId,t1.title,t1.description,t1.author
from tablename as t1
left join (select max(articleId) as articleId
from tablename
group by articleId ) as t2
on t1.articleId=tsm.articleId where [.....]

Categories