I would like to filtering database records if there is duplicate records I will mark the records as deleted = 1. Unfortunately I'm not able to update my records correctly, I did try use limit 1 for updating the records but I only update 1 record only and if I didn't use the limit 1 it will update entire records.
The above is my database table, what I need to do is, assume there is bunch of records with different point_id and I filtered to 1 only. Now I would like to query the records sort by date ASC and update all the records to deleted = 1 expect the last record.
Here is my source code. The problem I facing now is it will update all the records, and if I using LIMIT 1 it only will update 1 record only.
while($total > 1){
$total--;
$sql = sprintf("SELECT *
FROM customers_profiles_game_logs
WHERE point_id='$points_filter_row[point_id]'
AND customer_id='$sql_customer_row[customer_id]'
ORDER BY date_created ASC");
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($query);
$num_rows = mysql_num_rows($query);
for ($i = 1; $i < $num_rows; $num_rows--) {
echo $sqli = sprintf("UPDATE customers_profiles_game_logs
SET deleted='1'
WHERE customer_id='$sql_customer_row[customer_id]'
AND point_id='$row[point_id]' LIMIT 1");
mysql_query($sqli) or die(mysql_error());
}
}
You can have a subquery which gets the record to be updated and join it with the table itself, eg.
UPDATE customers_profiles_game_logs a
INNER JOIN
(
SELECT customer_id, MIN(date) date
FROM customers_profiles_game_logs
WHERE customer_id = 1 -- <== ID HERE
) b ON a.customer_id = b.customer_id
AND a.date = b.date
SET a.deleted = 1
if you remove the WHERE clause inside the subquery, all the first record for each customer will be updated.
you need this:
UPDATE customers_profiles_game_logs a
INNER JOIN
(
SELECT customer_id, MIN(date) date
FROM customers_profiles_game_logs
WHERE customer_id = 1 -- <== ID HERE
) b ON a.customer_id = b.customer_id
SET a.deleted = 1
http://sqlfiddle.com/#!2/6c440/1
another style:
UPDATE customers_profiles_game_logs a
INNER JOIN
(
SELECT customer_id, MIN(date) date
FROM customers_profiles_game_logs
) b ON a.customer_id = b.customer_id
SET a.deleted = 1
http://sqlfiddle.com/#!2/88e7c/1
Related
I have a table called bids, that have multiple rows.
these all have unique IDs however they have a listingID as well, so everytime it inserts it inserts a new row but with that listingID.
I'm trying to only return one unique result for the ListingID as appose to all the bids in the table , I tried SELECT DISTINCT and group by, but both didn't seem to work.
At the moment this is printing all the records from the table 'bids'
I would like to only print the last record for the listingID column.
$bids = $this->db->query("SELECT bidID,listingID, listing_title, bid_date, username,amount, starting_, sold, vintage, bottles, size, cases, sold_date, bid_type,
FORMAT(`bin`, 0) AS `bin`,
(CASE
WHEN ( SELECT COUNT(*) FROM bids WHERE bid_listing = listingID )
THEN
(SELECT FORMAT(amount,0) FROM bids WHERE bid_listing = listingID ORDER BY bidID DESC LIMIT 1)
ELSE
FORMAT(`starting_`, 0)
END
) AS `starting`
FROM (`bids`)
JOIN listings ON listingID = bid_listing
JOIN users ON list_uID = userID
WHERE bidder_ID = $userID
ORDER BY bidID DESC");
Try this sql. I used b1.* because I don't know what fields you're trying to return.
$bids = $this->db->query("select b1.* from bids b1
left join bids b2 on (b1.listingID = b2.listingID and b1.bidID < b2.bidID
where b2.bidID is null");
I'm having difficulty understanding how to Order a query by data from another table.
The existing query is: SELECT ID FROM UserTour WHERE Live = 1 ORDER BY LastUpdated DESC
This obviously Orders by the column 'LastUpdated' in the table 'UserTour'
However, I need it to be ordered by the column 'LastUpdated' which is in another table 'ImageLinks', Where 'TypeID' = 16 (again in 'ImageLinks').
I hope that makes sense.
So it would be something like: $ids = #mysql_values('SELECT ID FROM UserTour WHERE Live = 1 ORDER BY ('Select ID FROM 'ImageLinks' Where TypeID = 16 Order by LastUpdated DESC')');
Any help would be appreciated on how to do this. Cheers
If there is no relationship between the two tables your query in your question will look like this
select id from
(
SELECT
ID
, (Select ID FROM ImageLinks Where TypeID = 16
Order by LastUpdated DESC limit 1) as order_val
FROM UserTour
WHERE Live = 1
) x
ORDER BY x.order_val
which will work but will not do not any ordering as the order_val column will have a fixed value.
If the IDs are linked 1:1 (no indication that they are, but just supposin') we could do this:
select u.id
from UserTour u inner join ImageLinks i on u.ID = i.ID
where u.Live = 1 and i.TypeID = 16
order by i.LastUpdated desc
If the above is incorrect then you will have to decide how the two tables are related and join them correspondingly.
In other words, If the tables are in no way connected, then you cannot provide an ordering of one table's data based on a column in the other.
UPDATE
select
i.LinkID
, i.LastUpdated
from UserTour u inner join ImageLinks i
on u.ID = i.LinkID
where u.Live = 1 and i.TypeID = 16
group by i.LinkID, i.LastUpdated
order by i.LastUpdated desc LIMIT 30
I have a nested loop in my PHP code that is taking a long time and wondered of there was a way to speed this up:
$sql = "SELECT * FROM table_1";
$result = mysqli_query($sql);
while($row = mysqli_fetch_array($result)){
$sql2 = "
SELECT count(*)
FROM user_modules
WHERE
begin_ymdhi >= ".$date_from." AND
begin_ymdhi <= ".$date_to." AND
(
completed_ymdhi IS NULL OR
completed_ymdhi = ''
) AND
user_id = ".$row['user_id']." AND
task_id = ".$row['task_id']." AND
module_discon = 'N'
";
}
The outer query gets 1000 rows, the inner has to count across 10,000 rows - the run-time is around 115 seconds ! Is there any way to improve this method, either using a different technique or combined SQL query?
Don't use nested queries, combine them into a single query with a join:
SELECT t1.*, COUNT(u.user_id) ct
FROM table_1 t1
LEFT JOIN user_modules AS u ON u.user_id = t1.user_id AND u.task_id = t1.task_id
AND u.begin_ymdhi BETWEEN '$date_from' AND '$date_to'
AND u.module_discon = 'N'
GROUP BY t1.user_id, t1.task_id
Are the task_id's unique? if so, the most straight forward would be something like:
$sql2 = "
SELECT count(task_id) AS TaskCount
FROM user_modules
WHERE
begin_ymdhi >= ".$date_from." AND
begin_ymdhi <= ".$date_to." AND
(
completed_ymdhi IS NULL OR
completed_ymdhi = ''
) AND module_discon = 'N'
group by user_id
";
$result = mysqli_query($sql2);
SELECT user_modules.user_id, user_modules.task_id, count(*)
FROM user_modules LEFT JOIN table_1 USING (user_id, task_id)
WHERE
begin_ymdhi >= ".$date_from." AND
begin_ymdhi <= ".$date_to." AND
module_discon = 'N' AND
(
completed_ymdhi IS NULL OR
completed_ymdhi = ''
)
GROUP BY user_modules.user_id, user_modules.task_id
Append EXPLAIN before that entire SELECT statement (i.e EXPLAIN SELECT count(*)...) and MySQL will give you a run-down on what the select is doing.
Make sure the begin_ymdhi field is indexed properly. SHOW INDEX FROM table_2 to see.
I have this SQL Query:
SELECT
*,
COUNT(*) as count
from tickets
where
status = :status
and DATE(closed_timestamp) = '".date("Y-m-d")."'
group by assigned_to
order by count(*) DESC
LIMIT 3
but i want to remove the closed_timestamp column from the tickets table and run the query based on the datetime column in the ticket_updates table
ticketnumber in the tickets table is equal to the ticketnumber (multiple rows) in the ticket_updates table
so it should run the above query without the closed_timestamp column and base it on the latest datetime value in the ticket_updates table
EXAMPLE
there are 2 rows in the tickets table where ticketnumber = 1234 and 5678
there are 3 rows in the ticket_updates table.. two rows have ticketnumber = 1234 and the other has ticketnumber = 5678
i want to show all the rows from tickets where status = 'Completed' and the last update (ticket_updates table) equals the current date (2014-05-19)
Use join query like below,
SELECT
t.*,
COUNT(t.*) as count
from tickets as t
LEFT JOIN ticket_updates as tu
ON tu.ticketnumber = t.ticketnumber
where
t.status = :status
group by t.assigned_to
order by count(t.*) DESC
LIMIT 3
try this:
SELECT *
FROM tickets t
JOIN (
SELECT ticketnumber
FROM ticket_updates
WHERE DATE(datetime) = CURDATE()
) u
ON t.ticketnumber = u.ticketnumber
WHERE status = 'Completed'
I have a problem in fetching data from mysql database tables.
I have two tables like table-1 and table-2 in below figure. How to get data from table-2 when pilotid is not equal to 1 in table-1.
I'm not sure, if I understand correctly, but this returns all rows of table-1, that do not have a matching entry in table-2. You can find the respective documentation of NOT EXISTS here.
SELECT *
FROM table-1 t1
WHERE NOT EXISTS( SELECT * FROM table-2 t2 WHERE t1.`Venueid` = t2.`Venueid` )
select a.venueid, a.name
from table2 a, table-1 b
where b.pilotid <> 1 and b.venueid = a.venueid;
SELECT Table_2.*
FROM Table_2
LEFT JOIN Table_1
ON Table_2.Venueid = Table_1.Venueid
WHERE Table_1.Venueid != 1
OR Table_1.Venueid NOT IN(1, 13, 15);
$sql = "select Venueid from Table1 where pilotid <> 1";
$data = mysql_query($sql);
while($row = mysql_fetch_assoc($data))
{
$ids[] = $row['Venueid'];
}
$sql2 = "select * from Table2 where venueid IN(".implode(',', $ids).")";
$data2 = mysql_query(sql2);
//$data2 contains the result-set resource;