I have a table that contains some data. i have a 'username' field in my table that stores users username.
in this table there is possible that a user have many records.
now, how can i get the users that their username repeated more than X times? (50 time or more for example?)
and after that i want to delete rows for each user that i get in previous step but i need to keep first X rows and i need to delete all rows after row X for each user.
how can i do this with mysql and php?
update: i solve my problem with this:
SELECT username, count(*) as numRecords
FROM table
GROUP BY username
This will take a number of steps to achive..
Start by building a query to count the number of records for each user
SELECT username, count(*) as numRecords
FROM table
GROUP BY username
Then add:
HAVING numRecords > 5
to narrow down to usernames with more than 5 records..
Loop through the records from the query above..
foreach($results as $result){
// Query db using `username` to get the 'record to keep'
"SELECT * FROM table
WHERE username = $result['username']
ORDER BY someUniqueID
LIMIT 1"
__Execute the query__
__Store the record ID to keep__
// Delete records (except the one to keep)
"DELETE FROM table
WHERE username = $result['username']
AND someUniqueID != $someUniqueID"
__Execute the query__
}
SELECT DISTINCT `username`, COUNT(`username`) AS `numRecords`
FROM `table`
GROUP BY `username`
HAVING `numRecords` > 'someNumber'
Related
I have a database with 2 set of table which is Users and Record.so i want to list out latest record for each user in certain group but what happen is the result display the latest and the first record for user that i just update record which is '27/4/300' and '4/5/2108'.The date attribute which is 'tarikh' is in Record table,while users_id is in Users table.Do someone know better query to get the result that i want?
$sql = "SELECT * from Users, Record
WHERE Users.users_id = Record.users_id
AND Users.group_id='$users_group'
AND Record.tarikh IN (SELECT max(Record.tarikh) FROM Record
GROUP BY users_id)";
I am using sql server management studio 17
Try this.
$sql = "SELECT * from Users, Record
WHERE Users.users_id = Record.users_id
AND Users.group_id='$users_group'
AND Record.tarikh = (SELECT max(Record_nested.tarikh) FROM Record as Record_nested
where Record_nested.users_id = Record.users_id)";
I am creating a Log in and I have separate tables for Users A and Users B.
What I want to do is check first in first table if the Users that trying to Login is in the Table A,
if YES, it will not go to the Table B to check the Login credentials, if NOT, go to Table B and check the Login credentials.
Table A
SELECT * FROM tableA WHERE userId='$userId' AND password='$password'
Table B
SELECT * FROM tableB WHERE accountNumber='$accountNumber' AND password='$password'
Note: The 2 Tables has different Field Name userId and accountNumber.
I presume you are fetching the values of username and password from client side so I will tell you only what you asked for.
$getUserBasic1=$db->prepare('SELECT * FROM tableA WHERE userId="$userId" AND password="$password"');
$getUserBasic1->execute();
$user= $getUserBasic1->fetchAll();
if(count($user)>0)
{
//if yes do what you want here
}
else
{
$getUserBasic2=$db2->prepare('SELECT * FROM tableB WHERE accountNumber="$accountNumber" AND password="$password"');
$getUserBasic2->execute();
$user2= $getUserBasic2->fetchAll();
//write your code here
}
You could use an INNER JOIN and select both table results taking Table A's result first if it exists, else take Table B's result.
Assuming both tables have some sort of reference like the User ID you can use something like this:
SELECT tbla.*, tblb.* FROM tableA tbla
INNER JOIN tableB tblb ON tbla.userId = tblb.userId
WHERE userId='$userId' OR accountNumber='$accountNumber' AND password='$password'
ORDER BY userId ASC
LIMIT 1
The query above uses the cross-reference (userId in this case) and joins both tables together before querying the results. It orders the results by Table A before Table B but limits the result to 1 bringing either Table A or Table B out depending which is null.
Try combining the tables, some thing like:
SELECT * FROM tableA, tableB WHERE tableA.userId='$userId' AND tableA.password='$password' OR tableB.accountNumber='$accountNumber' AND tableB.password='$password'
I have not checked, so may not work, but see if this gets what you are looking for!
Something like this:
$sql = "SQL QUERY FOR TABLEA";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// checking if result in TABLE A
}
else{
//search in TABLE B by updating your sql value.
}
I hope that you want to check for the registered user, the best way to do that is to keep one table and just search there itself keeping the userID as the primary key.
I am pulling one column from the USERS table but now I wanna pull columns from the MONEY table. How do I accomplish this?
sample database
USERS TABLE
userID = 33
nestEgg = 600000
MONEY TABLE
userID = 33
monthlyContributions = 500, 250, 300
totalContributions =
<?php
include 'inc/connect.php';
$query = "SELECT * FROM USERS WHERE userID = '$userID'";
$result = mysqli_query($link,$query);
$row = mysqli_fetch_assoc($result);
?>
If I'm not mistaken, you're asking to create a column in MONEY which is the sum of nestEgg and monthlyContributions. I'm a total newbie, but I think getting the sum, followed by the insert, should look like:
SELECT (SELECT SUM(nestEgg) FROM USERS) + (SELECT SUM(monthlyContributions) FROM MONEY)
INSERT INTO MONEY(totalContributions)
If you only want the sum from the monthly contributions, then it should just be:
SELECT SUM(monthlyContributions) FROM MONEY
INSERT INTO MONEY(totalContributions)
If I'm not mistaken.
I'm developing a website using HTML, PHP and MySQL to access a database. On one page I present a table with data from that database. This is some of the code I'm using:
$sql1 = "SELECT * FROM MyTable ORDER BY ID ASC";
$rs1 = mysqli_query($link,$sql1);
(...)
while($row1 = mysqli_fetch_assoc($rs1)) {
echo "<tr><td>".$row1['ID']."</td><td>".$row1['Field1']."</td><td></td><td>".$row1['Field2']."</td><td>".$row1['Field3']."</td></tr>\n" ;
}
Notice the empty <td></td>? That's because I want to have there the number of time a given ID appears on two other tables (there are foreign keys involved, obviously). I have sorted out the code I need for that:
$sql2 = "SELECT (SELECT COUNT(*) FROM MyTable2 WHERE ID2=$row1['ID'])+(SELECT COUNT(*) FROM MyTable3 WHERE ID2=$row1['ID']) AS total";
However, I'm struggling with figuring out a way to add this result to the other table. Any help?
try with this.. it inserts the total to an table after selecting the count.
"INSERT INTO total_table (total)
SELECT (SELECT COUNT(*) FROM MyTable2 WHERE ID2=$row1['ID'])+(SELECT COUNT(*) FROM MyTable3 WHERE ID2=$row1['ID']) AS total
WHERE cid = 2"
So i have a problem i have a user table and a website table i need to select a random user from the users table just there username were there is a row in the website table with there username.Is this possible ?
So i am getting a random user table
$stmt9 = $db->prepare('SELECT * FROM users WHERE coins >= ? ORDER BY RAND() LIMIT 1');
$stmt9->execute( array('1') ) ;
$row = $stmt9->fetch();
Now some how i need to grab a random website were the owner = there username like so
$stmt21 = $db->prepare('SELECT * FROM websites WHERE owner = ? ORDER BY RAND() LIMIT 1');
$stmt21->execute( array($row['username']) ) ;
$row21 = $stmt21->fetch();
The problem i have is it will grab the username fine but then if the user has not submitted a website the second select will fail so some how i need to put both these select together. And grab a row of the website table were there is a row and were the coins in the user table is over 1.
You could check if the first query returns an empty set, anyway if you want one query and you are not interested in the username you could use this:
SELECT
*
FROM
websites w
WHERE w.owner
IN (SELECT u.username FROM users u WHERE u.coins >= ?)
ORDER BY
RAND()
LIMIT
1
If you want you can limit the username selected in the subquery adding the random order by and the limit clause.