Count entries from second Table that match id from first Table - php

This is basic but I can't figure it out. I have two tables (SeriesTable and OtherTable). SeriesTable has all the information for a given series including its id (column named "seriesid"). And OtherTable has a column called "seriescolumn" which also has the ids of a given series.
I need to make a query that counts every entry in OtherTable's "seriescolumn" that matches the seriesid column in SeriesTable. So for example, if the seriesid in SeriesTable is 5, I need to count how many entries in OtherTable have the value of 5 in the seriescolumn.
Below is my current code that simply grabs the info from the first table, but I have no idea how to correctly count the matching entries from OtherTable.
<?
$rs= mysql_query("SELECT seriesid FROM SeriesTable ORDER BY seriesid DESC");
while ($row= mysql_fetch_array($rs)) { ?>
content
<? } ?>

Sounds like you are going to need a join and group by statement.
SELECT s.seriesid, Count(*) As NumberOfSeries
FROM SeriesTable s Join
OtherTable o On s.seriesid = o.seriescolumn
Group By s.seriesid
ORDER BY seriesid DESC
This should return each seriesid and a count of how many times it was repeated.

Probably the easiest way to do this is in one big SQL query, using the count statement.
You can use a GROUP BY clause to group the result by the seriesid as you want, giving something along the lines of:
SELECT seriesid, COUNT(*) FROM SeriesTable, OtherTable
WHERE seriescolumn=seriesid GROUP BY seriesid

SELECT seriesid, COUNT(seriescolumn)
FROM SeriesTable, OtherTable
WHERE OtherTable.seriescolumn = SeriesTable.seriesid
GROUP BY seriesid;

Related

PHP SQL Query to get the most common value in the table

I'm trying to have my query count the rows and have it return the most common name in that list, then from that it counts how many times that name appears and outputs the name and the amount of times its there
This is the code I'm using:
$vvsql = "SELECT * FROM votes WHERE sid=? ORDER BY COUNT(*) DESC LIMIT 1";
$vvresult = $db->prepare($vvsql);
$vvresult->execute(array($_GET['id']));
$vvcount = $vvresult->rowCount();
foreach ($vvresult->fetchAll(PDO::FETCH_ASSOC) as $row) {
echo $row['username'];
echo $vvcount;
}
However, it just displays the first username in the table and counts up the entire table. I'm pretty new to this so I'm sorry if this is a bad post or if it didn't make much sense.
You would seem to want:
SELECT name, COUNT(*) as cnt
FROM votes
GROUP BY name
ORDER BY COUNT(*) DESC
LIMIT 1;
Note the GROUP BY. You may also want to filter by sid but your question makes no mention of that.
select username, count(*) as c
FROM votes
GROUP BY username
ORDER BY c DESC

Searching and Counting Data in PHP

I want to search data based on month and year. Then, it will count the same id for Book_id.
I have problems to count the Book_id for monthly. This query will count for entire records including monthly, which is not the result I want.
$res2 = mysql_query( "SELECT DISTINCT Date_borrow, Book_name as nmBook, Book_id as b_id, count(Book_name) AS count
FROM transaksi
GROUP BY nmBook
HAVING count > 1
ORDER BY COUNT DESC ");
$rowss = mysql_fetch_array($res2);
Thanks for your help.
I am taking a shot at it not knowing you complete data model
SELECT DISTINCT Date_borrow, Book_name as nmBook, Book_id as b_id,
count(Book_name) AS count
FROM transaksi
GROUP BY nmBook
HAVING count > 1
ORDER BY COUNT DESC
Should be:
SELECT Date_borrow, Book_name as nmBook, Book_id as b_id,
count(Book_name) AS counter
FROM transaksi
GROUP BY Book_name,Date_borrow,book_id
HAVING count(Book_name) > 1
ORDER BY `counter` DESC;
DISTINCT and GROUP BY are mutually exclusive: Once you use GROUP BY, apply either a function on all the fields or add the fields in the GROUP BY.
HAVING COUNT(Book_name): COUNT needs a parameter, so book_name in this case since that is the same as in your SELECT statement.
Use of just created alias in ORDER BY: Test that. Could be that you need to use COUNT(book_name) there too.
Use of reserved word "COUNT" as alias: Avoid the use of any terms sounding like functions or code in table names, column names, function names etc. Invent your own naming standard which avoids this use of (possibly) reserved key words.

Selecting the next results in MySQL

How can I select the next result just by specifying the name?
I have a table that looks like this, no IDs, just list of usernames.
row1 = username(Alex)
row2 = username(Bob)
row3 = username(Britney)
row4 = username(Steve)
row5 = username(Courtney)
row6 = username(Greg)
row7 = username(Abul)
row8 = username(Roger)
row9 = username(Victoria)
row10 = username(Brooke)
Let's say, I want to select all Items after 'Greg'. How can I achieve this?
No, there is no inherent ordering of tables in SQL, so there is no way (other than by alphabetical order) to determine which name comes next.
In fact, the order displayed in the question is entirely arbitrary - without a specified order by clause, retrieval order of rows is essentially random.
this can be done by two query..first find the id of the particular name.
like select id from tablename where username='Greg'
then fetching that id,
select * from tablename where id>fetching id.
Add ID column to your table, and then use LIMIT as offset
SELECT * FROM users LIMIT (SELECT ID FROM username WHERE username='Greg'), MAX(ID)
Didn't tested, but you can play with it

select 3 rows from mysql table, then get each row's specific column

Select 3 rows from table1
Get a specific column data out of each row.
Then use that each column data obtained , to make a query again to get data from table2.
Store the data obtained in step 4 into a variable for each row.
Then put them in json array (table 1 , 3 rows + table 2's data(each of them).
I am building a rank table, it displays top 3 users with their rank name.
For example:
User1 has 2000 points , user 2 has 4000points , user 3 has 10k points , so the top 3 user is :
user 3 > user 2 > user 1
So , i want the php to go to 'users' table and get the top 3 members using this:
$query = mysql_query("SELECT * FROM users ORDER BY pts DESC LIMIT 3");
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$rows[] = $r;
}
Table structure for 'user':
1.username(varchar)
2.pts(int)
After the rows are put into an array , how can i get 'points' for each of the row in that array.
Then go to 'rank' table to get their ranknames.
Table structure for 'rank':
1.rank(varchar)
2.pts(int)
Inside rank table there is 'pts' to let php choose compare which rank the user is at based on the points from each row of the array.
Normally i would use this if its only for 1 user , but for multiple users , im not sure:
$result = mysql_query("SELECT * FROM rank WHERE pts <= '$upts' ORDER BY pts DESC LIMIT 1")
or die(mysql_error());
Then after getting the rank for the top 3 users , php will now add the ranks to each of the user(row) in that array(of course , add it to the rank owner, not just simply place it in).
Then JSON encode it out.
How can i do this?
I am not sure if this is what you want. That is combine the two query into one query. Please take a look at http://sqlfiddle.com/#!2/ad419/8
SELECT user.username,user.pts,rank.rank
FROM user LEFT JOIN rank
ON user.pts <=rank.pts group by user.id
UPDATED:
For extracting top 3, could do as below;
SELECT user.username,user.pts,rank.rank
FROM user LEFT JOIN rank
ON user.pts <=rank.pts
GROUP BY user.id
ORDER BY pts DESC LIMIT 3
If i understand correctly, you need to get values from Rank and Users tables. In order to do that in just one query You need to add FK (Foreign Key) to the Rank table that points to a specific user in the Users table.
So you need to add userId to the Rank table and then you can run:
SELECT r.rank, u.points from users u,rank r where u.userId = r.userId
This is roughly what you need.
Not quite the answer to your exact question, but this might be of use to you: How to get rank using mysql query. And may even mean that you don't require a rank table. If this doesn't help, I'll check back later.
Use this query
$query = "SELECT
u.pts,
r.rank
FROM users as u
left join ranks as r
on r.pts = u .pts
ORDER BY pts DESC
LIMIT 3";
This will bring what you required without putting into an array
$rec = mysql_query($query);
$results = arrau();
while($row = mysql_fetch_row($rec)){
$results[] = $row;
}
echo json_encode($results);
It looks like what you're trying to do is retrieve the rank with the highest point requirement that the user actual meets, which isn't quite what everyone else is giving here. Fortunately it is easily possible to do this in a single query with a nice little trick:
SELECT
user.username,
SUBSTRING_INDEX(GROUP_CONCAT(rank.rank ORDER BY pts DESC),",",1) AS `rank`
FROM user
LEFT JOIN rank ON user.pts >= rank.pts
GROUP BY user.id
ORDER BY pts DESC
LIMIT 3
Basically what the second bit is doing is generating a list of all the ranks the user has achieved, ordering them by descending order of points and then selecting the first one.
If any of your rank names have commas in then there's another little tweak we need to add on, but I wouldn't have thought they would so I've left it out to keep things simple.

Selecting rows from a table by One a field from other table

What i want, to display rows from a table which is selected by a field from other table single value, lets say to display images from a table by last category id.
I have this type of query, but this return me all matching keys rows, if i inset LIMIT 1 then it return one row...
SELECT i.prof_image FROM profile_images i
JOIN images_cat cat ON (cat.cat_id = i.cat_id)
GROUP BY i.prof_image;
//OR LIMIT 1;
Any idea to fix this problem. (i.e. displaying the latest category images)?
This will work for your specific example.. If you need to be more selective, then please post some more details..
SELECT i.prof_image
FROM profile_images i
WHERE cat_id = (select max(cat_id) from images_cat)
SELECT * FROM table_1
LEFT JOIN table_2 ON table_1.id = table_2.id
This query will grab all things in table_2 that have the same id value.
Note that it is a LEFT JOIN - which means that if there are no matching values in table_2, it will still return the values from table_1.
What is your intent with using last()?
Hope this helps.

Categories