Count duplicates WHERE id=? - php

I want to be able to SELECT opponents id from a db table WHERE id=$currplayer.
My DB table is like this:
fk_player
fk_opponent
If I do like this:
SELECT fk_opponent
, COUNT(fk_opponent) AS oplay
FROM nf_newversus
GROUP BY fk_opponent
It does the thing right, but I want to be able to sort this so it is only the ones where fk_player = $currplayer... I have tried to insert a WHERE fk_player = $currplayer but that is not right...
Any help is appreciated.

SELECT fk_opponent
, COUNT(fk_opponent) AS oplay
FROM nf_newversus
WHERE fk_player = '$currplayer'
GROUP BY fk_opponent

This should be correct according to your description:
SELECT fk_opponent, COUNT(*) AS oplay
FROM nf_newversus
WHERE fk_player='$currplayer'
GROUP BY fk_opponent
If your table allows multiple player1 vs player2 (i.e. no UNIQUE(fk_player, fk_opponent) index), that should work just fine, but assuming you store matches in both ways.

Related

mysql How To join 2 column value into 2 column value

I have two tables with columns as follows:
khs (id, year, program, codemk)
subjects (id, year, program, codemk,namemk, tm, pr, lp)
I want to have a result containing:
codemk, namemk, tm, pr, lp
Note: Fields year, program and codemk in khs table each is not unique also in subjects table. But combine the 3 value of those fields make a unique value.
I tried this:
SELECT khs.id khs.codemk, subjects.namemk, subjects.tm, subject.pr, subjects.lp
FROM khs
RIGHT JOIN subjects
ON khs.year + khs.program +khs.codemk = subjects.year + subjects.program + subjects.codemk;
but the result for tm, pr and lp is not what I expected. What am I missing? Sorry I am new to MySQL and how do i create it to new table view.
Thanks in advance.
Maybe this:
SELECT khs.id khs.codemk, subjects.namemk, subjects.tm, subject.pr, subjects.lp
FROM khs
RIGHT JOIN subjects
ON khs.year=subjects.year, khs.program =subjects.program, khs.codemk = subjects.codemk;
But not sure if that is what you asked, otherwise:
SELECT khs.id khs.codemk, subjects.namemk, subjects.tm, subject.pr, subjects.lp
FROM khs
RIGHT JOIN subjects
ON CONCAT(khs.year,khs.program, khs.codemk) = CONCAT(subjects.year, subjects.program, subjects.codemk);
Why use a join? Why not try something like this:
SELECT codemk,namemk,tm,pr,lp
FROM khs,subjects
WHERE khs.year = subjects.year
I am not sure what is your result expectetions (could you provide it please? as well as samples of data tables) but you can try for now:
SELECT khs.id khs.codemk, subjects.namemk, subjects.tm, subject.pr, subjects.lp
FROM khs
INNER JOIN subjects
ON khs.year = subjects.year
AND khs.program = subjects.program
AND khs.codemk = subjects.codemk;

How to count if value of a variable is repeated?

I am learning how to work with MySQL, and at the moment I succeed to show data from my table, using:
while($objResult2 = mysqli_fetch_assoc($objQuery_product)) {
Results are shown by using this variable $objResult2["id_product"]; this way i can take from DB any field I want like: $objResult2["name"]; $objResult2["email"]; etc.
But what i do if i have in the table more rows with the same id_product?
I want to write a if statment, which counts if id_product repeats. How to do that? If it is a lot of work, atleast please give me an idea of the right tutorial that I must read. Because i am trying second day to fix this, and searched google but i didnt find what i need, or maybe i coulndt understand it....
This is my query
$sql_product = "SELECT * FROM ps_product AS prod";
$join_product = " LEFT JOIN ps_product_lang AS lang ON lang.id_product = prod.id_product";
$join2_product = " LEFT JOIN ps_stock_available AS stok ON stok.id_product = prod.id_product";
$where_product =" WHERE prod.id_category_default = $idp AND lang.id_lang = 8";
$sql_product = $sql_product.$join_product.$join2_product.$where_product;
$objQuery_product = mysqli_query($objConnect, $sql_product) or die ("Error Query [".$sql_product."]");
You can simple remove the same id_product using DISTINCT keyword in your query. Such as:
SELECT DISTINCT id_product FROM my_table
This will give you results with different ids only.
The second way of doing it is taking the output values inside an array.
In your while loop:
$my_array[] = $objResult2["id_product"];
Then using array_filter remove all the duplicates inside the array.
YOu can also use array_count_values() if you want to count the duplicate values.
Ok here we go. For example you are fetching data with this query.
select id_product, name from PRODUCTS;
Suppose above query gives you 5 records.
id_product name
1 bat
2 hockey
2 hockey
3 shoes
4 gloves
Now you got 2,2 and hockey, hockey. Instead of thinking this way that you have to introduce an if statement to filter repeating records or same name or id_product records.
Rewrite your sql query like this.
select distinct id_product, name from PRODUCTS;
Or if you need count of each then my friend you will write your query something like this...
Graham Ritchie, if Andrei needs count of each repeating record then we will do something like this in our query.
SELECT PRODUCT_ID,
COUNT(PRODUCT_ID) AS Num_Of_Occurrences
FROM PRODUCTS
GROUP BY PRODUCT_ID
HAVING ( COUNT(PRODUCT_ID) > 1 );
SELECT id_product,COUNT(*) AS count
FROM tablename
GROUP BY id_product;
This query will then return you two items in your query
$objResult2["id_product"] //and
$objResult2["count"]
The if statement is then just
if($objResult2["count"] > 1){
//Do whatever you want to do with items with more than 1 occurence.
//for this example we will echo out all of the `product_id` that occur more than once.
echo $objResult2["id_product"] . " occurs more than once in the database<br/>";
}

Count duplicate values and display each different value from mysql table using PHP

I have a table (url_log) with a column (referer) of urls. Some urls are unique and some are duplicates. Using PHP I want to display each different url (without repeating) and the number of times the url appears in the column.
This is what I came up with but it is definitely wrong:
echo '<table>';
$ref=$icdb->get_row("SELECT COUNT(referer) AS frequency, referer FROM url_log WHERE u = '".$dom."' GROUP BY referer ORDER BY frequency DESC");
foreach ($ref as $details) {
echo "<tr><td>".$details['referer']."</td><td>".$details['frequency']."</td></tr>";
}
echo '</table>';
Any tips?
If I understand your question, this should do it.
SELECT DISTINCT(referer), COUNT(referer) AS frequency
FROM url_log
GROUP BY referer
ORDER BY frequency DESC;
for selecting each different value of a column use this query
SELECT DISTINCT(column) AS columnname_key FROM table ;
to count duplicate use this code
SELECT Count(*) duplicatetable
FROM
(
select columname_to_check_dulicate_values, Count(*)
from tablename
group by name
having Count(*) > 1
) x

SQLite3 duplicates

I'm having difficulties with SQLite3. The table is as follow:
id|name
11|test1
31|test1
51|test1
13|test2
17|test2
..|..
I need to get only one name and all id's for that name, like this:
test1|array(11,31,51)
test2|array(13,17)
...
How can I do it with PHP and SQLite3? Thank you.
use group_concat
SELECT
name,
group_concat(id) AS ids
FROM Table
GROUP BY name
will return something like
test1|11,31,51
test2|13,17
and then you can just explode the ids, to get them as array.
$ids_array = explode(",",$ids);

Update values of database with values that are already in DB

I've a database that stores data read from different sensors. The table looks like this:
[SensorID][timestampMS][value]
[Sensor1][123420][10]
[Sensor1][123424][15]
[Sensor1][123428][6554]
[Sensor1][123429][20]
What I would like to do is the following: There are some reads that are corrupted (numbers that are 6554), and I would like to Update that with the next value that is not corrupted (in the example shown below that would be 20). So, if a number is 6554, I would like to update that with the next value (in timestamp), that is not corrupted.
I was thinking on doing this in PHP, but I wonder if it's possible to do it directly with a SQL script.
Appreciate :)
You can use a correlated sub-query...
UPDATE
myTable
SET
value = (SELECT value FROM myTable AS NextValue WHERE sensorID = myTable.SensorID AND timestampMS > myTable.timestampMS ORDER BY timestampMS ASC LIMIT 1)
WHERE
value = 6554
The sub-query gets all the following results, ordered by timestampMS and takes just the first one; That being the next value for that SensorID.
Note: If no "next" value exists, it will attempt to update with a value of NULL. To get around this, you can add this to the WHERE clause...
AND EXISTS (SELECT value FROM myTable AS NextValue WHERE sensorID = myTable.SensorID AND timestampMS > myTable.timestampMS ORDER BY timestampMS ASC LIMIT 1)
EDIT
Or, to be shorter, just use IFNULL(<sub_query>, value)...
Not sure if this is valid syntax, can't test it ATM. You may need to change this to be JOINs instead of the nested subqueries, but in concept you can do something like (for SQL Server):
UPDATE t1
SET Value = ( SELECT Value
from MyTable t2
WHERE t2.SensorID =t1.SensorID
AND t2.[timestamp] =
( SELECT MIN([TimeStamp])
FROM mytable t3
where t3.sensorid = t2.sensorID
AND t3.[timestamp] > t2.[timestamp]
)
)
FROM Mytable t1
WHERE t1.value = 6554
I did a workaround based on Dems solution, and it works in Mysql:
I've created a "copy" of the sensors table like this:
drop table if exists sensors_new;
create table if not exists sensors_new like sensors;
insert into sensors_new select * from sensors;
Then I do what Dems recommended me doing, but using this new aux table in the select (to avoid the error that Mysql launches when Updating a table while doing a select in the same table).
UPDATE
sensors
SET
raw_data = (SELECT raw_data FROM sensors_new AS NextValue WHERE sensor_id = sensors.sensor_id AND timestampMS > sensors.timestampMS ORDER BY timestampMS ASC LIMIT 1)
WHERE
value = 6554
Then, just drop this auxiliar table.
I hope this helps Mysql users.

Categories