Mysql removing duplicates based on one column - php

I am using the query below
$result2 = mysql_query("select * from HandsetStock WHERE SubCategory NOT LIKE '%clearance%'", $dbh2);
I am getting a few duplicate results which I want to eliminate from the results however they are not completely duplicate rows. The column name is Make. I am guessing i need some kind of subquery but I am struggling to get it to work for me. Basically I need to select all records but where Make has the same value just the first record.
Thanks

$result2 = mysql_query("select * from HandsetStock
WHERE SubCategory NOT LIKE '%clearance%'
group by Make", $dbh2)

Related

Count how many rows that have a special value in a column

I'm trying to count how many rows that have the same value as a variable.
Then I wanna echo out the number that is calculated in the mysql query!
Is this possible?
Here is a image of my database:
http://img812.imageshack.us/img812/333/9jr1.png
Sorry for my bad English and if the question is hard to understand (new to this stuff)
Here it is from your old question
$query= "SELECT pic_name, count(pic_name) as count FROM hulebild_likes where pic_name='$bild_id'";
$likesf = mysqli_query($con, $query);
$row=mysqli_fetch_array($likesf);
echo $row['count'];
There are two different approaches here. If you're looking for a specific value and know it in advance, you can do something as simple as:
select count(*) as count from table where column = 'value';
Alternatively, if you're just looking for a count of duplicate values, you could go with something like:
select count(*) as count, column from table group by column;
That will give you two columns: your column of values and how many occurrences there are of each value.
Execute a SQL query like this:
SELECT COUNT(*) FROM yourtablename WHERE yourcolumnname = yourvariablevalue;

select and update mysql same query

I'm running a query to select an array of id's from one table, so that I can update another table with the data from the resulting dataset.
//db query result
$query = "SELECT image_id FROM jos_jxgallery_images ORDER BY jos_jxgallery_images.image_id DESC LIMIT 25";
$query_execute = mysql_query($query);
mysql_close($db_config);
while ($items = mysql_fetch_array($query_execute)) {
echo $items['image_id'];
echo '<br/>';
}
I think I need to do it in the while loop, I just have the echo there to see what's in items variable. That works ok. I think the thing to do is in the while loop..I'd like to replace the 'echoing' with an actual update SET query for my other table. Something like...
while ($items = mysql_fetch_array($query_execute)) {
$q = "UPDATE jx_gallery_images_ratings SET image_id ='".$items."";
mysql_query($q);
But the new table has no data. Is there just a better way to write this...maybe even as one query or something? Any help is appreciated.
EDIT: I should explain a little better. The table is empty, and I could go ahead and use an insert from one table to another just to get the id's there. However, after that...in a way it is somewhat a 'temp' table. But not really. Whatever ordering of image_id's I have created in my SELECT query from my first table (There are other rows to sort by other than image_id, like 'hits', for example)...so the second table needs to be updated with the same ordering of image_id's. Probably be running this several little snippet several times with a cron job. So, yeah, I'm trying to update the second table with the ordering of the SELECT query of the first table and just put the id's in my second table, again...according to the order of the first SELECT query.
If the table is empty, you should do an insert. You can do it in a single query like this:
INSERT INTO jx_gallery_images_ratings (image_id)
SELECT image_id FROM jos_jxgallery_images ORDER BY jos_jxgallery_images.image_id DESC LIMIT 25
Note that you probably wouldn't really need the ORDER BY, adn you could do it for all images at once by removing the LIMIT
Something like:
UPDATE tbl_updateme SET row_to_update = (SELECT row_you_need from tbl_target WHERE tbl_updateme.comparison_row = tbl_target.comparison_row)
INSERT INTO jx_gallery_images_ratings (image_id) (SELECT image_id FROM jos_jxgallery_images ORDER BY jos_jxgallery_images.image_id DESC LIMIT 25)
Or
Easy way is create trigger that updates table after selection with Dynamic SQL

Counting occurences in second table compared to first

I have two tables, one holds the information of contributors to my site and one holds information on photographs contributed.
For the admin side of the site, I want to create a table using php and mysql that displays all contributors but also counts the number of photographs each contributor has available for the site.
I get the list of names using this code
SELECT *
FROM site_con
ORDER BY surn ASC
I have then set up a loop to list all the names but have added a query within that loop to count the number of photographs using this code
$contributor = $row_rsContrib['con_Code'];
mysql_select_db($database_connGrowl, $connGrowl);
$query_rsCounter = "SELECT COUNT(*) AS Count
FROM site_phts
WHERE photter = $contributor";
$rsCounter = mysql_query($query_rsCounter, $connGrowl) or die(mysql_error());
$row_rsCounter = mysql_fetch_assoc($rsCounter);
$totalRows_rsCounter = mysql_num_rows($rsCounter);
The only problem is when '$contributor' is not in the photographs table, it returns an error.
Any ideas?
You can get the list of contributors & the number of photos in a single query:
SELECT sc.*,
COALESCE(x.numPhotos, 0) AS numPht
FROM SITE_CON sc
LEFT JOIN (SELECT sp.photter,
COUNT(*) AS numPhotos
FROM SITE_PHTS sp
GROUP BY sp.photter) x ON x.photter = sc.con_code
ORDER BY ssc.surn
Your query fails because a photographer doesn't necessarily have contributions -- the query above returns the list of photographers, and those without photos associated will have a numPht value of zero. Here's a primer on JOINs, to help explain the OUTER JOIN that's being used.
Actually the best way to do this is by using MSQL to count rather than PHP:
SELECT site_con.*, COUNT( photo_id )
FROM site_con
LEFT JOIN site_phts ON site_con.con_Code = site_phts.photter
GROUP BY site_con.con_Code
ORDER BY site_con.surn
The LEFT JOIN has the special property of creating NULL entries when there is no row in the right table (photos) that matches a contributor row. COUNT will not count these NULL entries. (You need some unique column in the photos table, I used photo_id for that.)
this is the relation between Contributors and photographs:
1 photograph can have a most 1 Contributor
1 Contributor can have a most infinit photograph
Contributor <-(0,n)------(0,1)-> Photograph
so you might wanna add a connexion betweet those two tables, I mean you add the con_id to the photographs table (as a column).
this way you'll be able to retrieve all the informations in one SQL query.
(like OMG Ponies just said)
Do something like this, I believe this should work :
$result = mysql_query("SELECT COUNT(*) AS Count FROM site_phts WHERE photter = '$contributor'"); // put the single quote if $contributor is a string value
//use mysql_fetch_array
if ($row = mysql_fetch_array($result, MYSQL_NUM)) {
printf("ID: %d", $row[0]);
}
Hopefully this works, Good luck mate !

phpMyAdmin versus mysql_fetch_array - why can't I get GROUP BY to work?

I have a simple table called "board" that has a column called "sid" - that is just integers. Many of these are duplicates. I want to know only distinct values in this column, so I do this:
SELECT sid FROM board GROUP BY sid
When I run this query directly in phpMyAdmin, I get the set I was expecting. No problem. However, this bit of code returns every row in the entire table, without exception:
$sql = "SELECT sid FROM board GROUP BY sid";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
echo $row["sid"] . "<br />";
}
Does anyone know why? FYI I've tried every combination of DISTINCT and GROUP BY I could think of, but no matter what I do, I can't get a distinct set to echo out.
That sounds like very strange behavior, but why don't you try this:
select distinct sid from board
ACK. PEBKAC, sorry. Thanks for all the help. I didn't realize I had it nested in another loop and so the distinct resultset was actually echoing out multiple times.

Count rows from results of a "mysql_query"

If I have this:
$results = mysql_query("SELECT * FROM table_name WHERE id=$id");
is there then any way to check how many rows which have a field-value of "Private" or "Company" ?
I need to show the user how many "Private" and "Company" records where found, without making another query. (There is a column called 'ad_type' which contains either "private" or "company")
I already know the mysql_num_rows for counting all rows!
EDIT:
There are 500thousand records! So maybe an iteration through the result is slow, what do you think?
Thanks for all help :)
The above answers are great and all, but the currently checked answer will work very inefficiently should you be dealing with a large amount of data
Example of the above answer (via Gal)
$results = mysql_query("SELECT *,(SELECT COUNT(*) FROM table_name WHERE column=$value) count FROM table_name WHERE id=$id");
It's good and all, and it returns what you need but the obvious design flaw is that making your SQL server return the results then re-return them and look at just the count is very inefficient for large amounts of data.
Simply do this:
$results = mysql_query("SELECT * FROM table_name WHERE column=$value");
$num_rows = mysql_num_rows($result);
It will yield the same results and be much more efficient in the long run, additionally for larger amounts of data.
You can do something like:
$results = mysql_query("SELECT *,(SELECT COUNT(*) FROM table_name WHERE column=$value) count FROM table_name WHERE id=$id");
in order to fetch the number with sql.
If you don't want to change your query you could do a
$results = mysql_query("SELECT * FROM table_name WHERE id=$id");
$count = mysql_num_rows($results);
steps to get a count():
use mysql_query() to get count,
use mysql_fetch_array() to get the only 1 row
get the only one column of the row, this is the count,
here is an example, which check whether the email is already used:
// check whether email used
$check_email_sql = "select count(*) from users where email='$email'";
$row = mysql_fetch_array(mysql_query($check_email_sql));
$email_count = $row[0];
Iterate through the result set of rows and count the number of occurences of Private and Company in ad_type, respectively?
You can do
SELECT COUNT(*) FROM table_name WHERE id=$id GROUP BY fieldvalue HAVING fieldvalue = "Private"
SELECT COUNT(*) FROM table_name WHERE id=$id GROUP BY fieldvalue HAVING fieldvalue = "Company"
but that would be another query. But if you process the data anyway, you could simply sum up the number of "Private" and "Company" rows after doing the query.
In the case you don't have to get all results, use this.
SELECT ad_type, COUNT(*)
FROM table_name
WHERE (id=$id)
GROUP BY ad_type
HAVING ((ad_type = 'Private') OR (ad_type = 'Company'))
If you still have to fetch all the records where id = $id, it won't work. But executing such a query (once) before fetching the real data should be more efficient than using a subquery.
I guess this query would do the job:
SELECT ad_type, count(*) FROM table_name WHERE id=$id GROUP BY ad_type;
I don't see any reason so far to use HAVING, since you probably want to show the user an overview of all the ad_type's found in DB (at least you didn't mention that there are other values for ad_type then the two given).
I also strongly suggest NOT to use sub-queries; always try to use just one.
If there's one thing that will slow your query down, it's a subquery (or subqueries).
Good luck!
Iterate through the results of the query and keep a count of how many of each show up in local variables.

Categories