SQL Query count issue - php

I've two tables artist and members. artist has zero to many relation with members. (one artist may have 0 or many members)
So, I want to get all the fields of artist with the total number of members, that he has.
I write a query, but, it returns 0 count if there is no artist in the table (artist table is empty). I am using this query
SELECT a.artistname, count(m.id) as total
FROM artist a, members m
WHERE m.artist_id = a.id
It should simply not return anything if there is no artist.
Thank you!

I'm assuming that your field name is artistname in the artist table,
The query should go like this:
SELECT artist.artistname, COUNT(members.id) AS total_members
FROM artist
LEFT JOIN members ON members.artis_id = artist.id
GROUP BY artist.artistname
Use join, and to use sql count you need to use group by.

Perhaps the artistname is empty. Did you check the data? You could try the following modified query:
SELECT a.artistname, count(m.id) as total
FROM artist a, members m
WHERE m.artist_id = a.id
AND a.artistname is NOT NULL
AND a.artistname <> '';

This should work:
SELECT a.artistname,
count(m.id)
FROM artist a
LEFT JOIN members m
ON m.artist_id = a.id;

Related

Sorting through 3 tables MYSQL

Hello I am trying to sort through these 3 Tables
I need to create a query that goes through the 'Author' Table,
grabs the author num
Then goes to the 'Wrote' table to find the 'BookCode' from the AuthorNum of the last table
Then to finally go through the Book table to list the title of the book and the first name and last name of the author.
I was thinking of using a join table but am not too solid on my uinderstanding on how it works. Nested select statements was my next guess but I can't get them to go through so many tables.
If anyone could help me that would be fantastic, thank you.
You want to use INNER JOINS to match up the data
SELECT *
FROM authors AS a
INNER JOIN wrote AS w
ON a.AuthorNum = w.AuthorNum
INNER JOIN book AS b
ON w.BookCode = b.BookCode
Please try to use this :
(I named the first table name to first)
Select a.Title as title, w.AuthorFirst as firstName, w.AuthorLast as lastName
From wrote as w
Inner Join author as a
Inner Join first as f
On (Select ww.AuthorNum From WroteTable as ww Order By DESC LIMIT 1) = f.AuthorNum
On f.BookCode = a.BookCode

joining 2 tables in msqli

table posts
table users
how would i count posts for specific user logged in. for example when user with id 3 is logged in it should show me 4 posts
I already did it for total posts count:
<?php
$post_query1 = "SELECT count(*) AS total FROM posts ";
$post_result1 = mysqli_query($db, $post_query1);
$post1 = mysqli_fetch_array($post_result1);
?>
Try below example :
select count(*) as total from user as u inner join post as p on p.id_user = u.id_user AND u.id_user = 3
If you want to get only the posts count for the particular user, say user with id = 3, your query should be this:
$query = "SELECT count(*) AS total FROM posts WHERE id_users = 3";
But if you want to get both the posts count as well as the user information and other post information, you will have to run a join query on both the users and posts table. Your query would now become:
$query = "SELECT u.*, p.*, count(p.id_posts) FROM users AS u JOIN posts AS p ON u.id_users = p.id_users WHERE p.id_users = 3";
Some Useful Notes
p.* - * is a wildcard character that means get all the columns in the posts table
u.* - * is a wildcard that means get all the columns in the users table
posts as p - AS is for aliasing. So, we are giving posts table a temporary name.
Here are the different types of the JOINs in SQL:
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from the right table
RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records from the left table
FULL (OUTER) JOIN: Return all records when there is a match in either left or right table
Note: It is necessary that you have to join two/more tables only with the help of foreign key. Without the foreign key is is meaningless to join two or more tables
Reference 1: https://www.w3schools.com/sql/sql_join.asp
Reference 2: https://www.tutorialspoint.com/mysql/mysql-using-joins.htm
As per the Question what you have asked to join the tables
Query:
SELECT * FROM TABLE 1 JOIN TABLE 2 ON TABLE1.id = TABLE2.id WHERE TABLE2.ID=3
Kindly replace TABLE1 & TABLE2 with the Tables that are to be joined and the id with the foreign key what you have specified in the Table.
Hope so this might be helpful for you to write your own code in future. Happy Coding :)
You have only to use a simple join.
SELECT count(*)
FROM USER u,
post p
WHERE p.id_user = u.id_user
AND u.id_user = 3

joining tables with same categories

I'm trying to join 2 tables with same categories but it's not quite working, its not returning results.
I have 2 tables tvshows and movies and both of them have columns categories now i want to go through all of them and see if categories match and return them but I don't know what is wrong with this. Please take a look, thanks!
$query = $connection->prepare("
SELECT
a.id,
a.hash,
a.categories,
a.thumb_location,
a.name,
a.year,
b.id,
b.hash,
b.categories,
b.thumb_location,
b.name,
b.year
FROM movies AS a
LEFT JOIN series AS b
ON a.categories = b.categories
WHERE a.categories LIKE ? OR b.categories LIKE ? ORDER BY a.id DESC
");
You are using column named categories in WHERE part of your query, but there are two columns with this name in tables movies and series, so database won't know, which column to search in.
You have to specify probably WHERE a.categories LIKE ? OR b.categories LIKE ? if you want to find rows, where some category is set for movie or series.
If you want to search for movies and series pairs by categories, you should join them by that column. But if categories is something like "Comedy,Action" etc. it won't work. You should consider remodeling database and create table categories and then movies_categories with ID of movie and ID of category rows and series_categories with same structure. Than you will be able to do lot's of queries for selecting movies that has categories same as series etc.
I'm not sure I've understood very well, but give this a try:
$query = $connection->prepare("
SELECT a.hash,
a.categories,
a.thumb_location,
a.name,
a.year,
b.hash,
b.categories,
b.thumb_location,
b.name,
b.year
FROM movies AS a
LEFT JOIN series AS b
ON a.hash = b.hash
WHERE a.categories = b.categories ORDER BY id DESC
");

Returning a single record from many to many table

I have a table structure like following:
Users => Histories <= Brands
Histories table keeps following columns: userId, brandId, points
I have a query like following:
select b.id, sum(h.points),h.brandId
from brands b left join
histories h
on b.id = h.brandid and h.userId = 2866
group by b.id;
This query returns me brands where USER made points and didnt make any points at all..
I wanna add a filter to a brandId as well so that the query doesn't returns all results, but a single result at a time depending what brandId has been sent to the query... How can I and where can I add a statement which would return me a single record for this query?? So basically I just need to pass brandId = to something statement, leaving the query it self as it is right now ... :)
For example if brand id is 100:
select b.id, sum(h.points),h.brandId
from brands b left join
histories h
on b.id = h.brandid and h.userId = 2866
where b.id=100
group by b.id
limit 1;

Retrieving count of column mySQL PHP

Hey guys I have a mysql table called interests with 4 columns. interestID, name, categoryID interest_desc and date. the categoryID column is linked to a seperate table. How would I use a mysql query that checked how many interests are in a certain category?
Im guessing i use some sort of count() query?
Thanks guys
Update -
$count_query_v1 = "SELECT categoryID, COUNT(*) AS total FROM interests GROUP by categoryID; "; $answer = mysql_query($count_query_v1) or die(mysql_error()); echo $answer;
Getting closer but still not perfect, i want to echo out the categoryID with the most interestID's
select category_name, count(*) as total
from interests i left join category c on c.category_id = i.category_id
group by i.category_id;
count + group by,
assuming interestID is the unique primary key,
and each interest is tied to single category (as what you have shown)
select categoryID, count(*) as total
from interests
group by categoryID;
// the above example is a simple group by ID without using inner join
output :-
categoryID, total
SELECT COUNT(interestID) FROM interests WHERE categoryID = 'yourvalue';
SELECT COUNT(interestID), categoryID FROM interests GROUP BY categoryID;
Since you are using the insert query each query will insert one record, so just count the number of insert queries you run by using a counter varialble.

Categories