I have 3 tables "maintenances", "cars", "users" . I want to select all data from table maintenance with a distinct car_id and the last record for each distinct (based on max maintenance_date)
SELECT
m. * , u.username, c.Model, c.Make, c.License, c.Milage, COUNT( m.process_id ) AS count_nr
FROM
maintenances AS m
LEFT JOIN users AS u ON u.id = m.user_id
LEFT JOIN cars AS c ON c.id = m.car_id
WHERE
maintenance_date = (SELECT MAX(maintenance_date) FROM maintenances WHERE car_id = m.car_id)
The problem is that this query returns only one record which has the max date from all records. I want all records (distinct car_id and from records with the same car_id to display only values for max(maintenance_date))
This is your query:
SELECT m. * , u.username, c.Model, c.Make, c.License, c.Milage, COUNT( m.process_id ) AS count_nr
----------------------------------------------------------------^
FROM maintenances AS m LEFT JOIN
users AS u
ON u.id = m.user_id LEFT JOIN
cars AS c
ON c.id = m.car_id
WHERE maintenance_date = (SELECT MAX(maintenance_date) FROM maintenances WHERE car_id = m.car_id);
It is an aggregation query. Without a group by, only one row is returned (all the rows are in one group). So, add the group by:
SELECT m. * , u.username, c.Model, c.Make, c.License, c.Milage, COUNT( m.process_id ) AS count_nr
FROM maintenances AS m LEFT JOIN
users AS u
ON u.id = m.user_id LEFT JOIN
cars AS c
ON c.id = m.car_id
WHERE maintenance_date = (SELECT MAX(m2.maintenance_date) FROM maintenances m2 WHERE m2.car_id = m.car_id);
GROUP BY c.id
I also fixed the correlation statement, to be clear that it is correlated to the outer query.
add GROUP BY u.username .
WHERE
maintenance_date = (SELECT MAX(maintenance_date) FROM maintenances WHERE car_id = m.car_id)
GROUP BY u.username
Related
I have three tables, users(which includes user details), territory_categories(which has different territory names and their ids), user_territory(a junction table between the two)
I want to filter users based on selected territory from the list.
query for that is --
SELECT u.id,account_id_fk,first_name,last_name,email_address,password,mobile_number,gender,user_accuracy,check_in_radius,report_to,role,allow_timeout,
active,last_logged_on,last_known_location_time,last_known_location,u.created_on,u.created_by,
(SELECT COUNT(DISTINCT u2.id) FROM fieldsense.users u2
INNER JOIN user_territory t1 ON u2.id=t1.user_id_fk
INNER JOIN territory_categories c on c.id=t1.teritory_id
**WHERE c.category_name LIKE** "Gujarat" AND(u2.account_id_fk=1 AND u2.role!=0) ) AS usersCount,
IFNULL(a.id,0) attendanceId,IFNULL(a.punch_date,'1111-11-11') punchInDate,IFNULL(a.punch_in,0) punchIntime,IFNULL(a.punch_out_date,'1111-11-11') punchOutDate, IFNULL(a.punch_out,0) punchOutTime
FROM fieldsense.users as u
LEFT OUTER JOIN attendances as a ON u.id=a.user_id_fk AND a.id=(select max(id) from attendances att where att.user_id_fk=u.id)
INNER JOIN user_territory t1 ON u.id=t1.user_id_fk
INNER JOIN territory_categories c on c.id=t1.teritory_id
**WHERE c.category_name LIKE "Gujarat"**
GROUP BY u.id **limit 10**
OUTPUT :
usersCount: 136
attendanceId: 0
punchInDate: 1111-11-11
punchIntime: 0
punchOutDate: 1111-11-11
punchOutTime: 0
10 rows in set (2.06 sec)
And without where clause when it loads it takes almost 1 minute to display the data
OUTPUT without where clause :
usersCount: 144
attendanceId: 0
punchInDate: 1111-11-11
punchIntime: 0
punchOutDate: 1111-11-11
punchOutTime: 0
10 rows in set (54.45 sec)
I am getting the desired output, but query is taking almost 1 minute to load, which i want to optimize. how can i do this ?
Try this out. I just narrowed down your inner join on table user_territory, so it will not join whole user_territory table but will only join distinct user_ids in it. Hope it reduces the performance time,
SELECT u.id,
account_id_fk,
first_name,
last_name,
email_address,
PASSWORD,
mobile_number,
gender,
user_accuracy,
check_in_radius,
report_to,
role,
allow_timeout,
active,
last_logged_on,
last_known_location_time,
last_known_location,
u.created_on,
u.created_by,
(
SELECT
COUNT(u2.id)
FROM
fieldsense.users u2
INNER JOIN (SELECT DISTINCT user_id_fk as id, territory_id FROM user_territory ) t1 ON u2.id = t1.id
INNER JOIN territory_categories c ON c.id = t1.teritory_id
WHERE
c.category_name LIKE "Gujarat"
AND (
u2.account_id_fk = 1
AND u2.role != 0
)
) AS usersCount,
IFNULL(a.id, 0) attendanceId,
IFNULL(a.punch_date, '1111-11-11') punchInDate,
IFNULL(a.punch_in, 0) punchIntime,
IFNULL(
a.punch_out_date,
'1111-11-11'
) punchOutDate,
IFNULL(a.punch_out, 0) punchOutTime
FROM
fieldsense.users AS u
LEFT OUTER JOIN attendances AS a ON u.id = a.user_id_fk
AND a.id = (
SELECT
max(id)
FROM
attendances att
WHERE
att.user_id_fk = u.id
)
INNER JOIN (SELECT DISTINCT user_id_fk as id, territory_id FROM user_territory ) t1 ON u2.id = t1.id
INNER JOIN territory_categories c ON c.id = t1.teritory_id
WHERE
c.category_name LIKE "Gujarat"
GROUP BY
u.id
LIMIT 10
I have 4 table and i want to extract: id, nume, localitate, masina_id, nr_inmatriculare, an_fabricatie, rafinarie, marca, and sum (quantity+deliver_quantity) as total_quantity group by an_fabricatie , Order by marca, and put some having clouse.
I don’t know how to make this.
My query is as bellow , but I think isn't correct.
select c.id, c.nume,c.localitate,l.masina_id, i.nr_inmatriculare, i.an_fabricatie,
i.rafinarie, m.marca from clienti c inner join livrari l on c.id = l.id inner join incarcari I on l.incarcare_id = l.livrari_id inner join masina m on i.id_marca = m.id, sum(select quantity, deliver_quantity) as total_quantity group by an_fabricatie having quantity >1000 order by marca;
Incarcari table
Id|livrari_id|id_marca|nr_inmatriculare|an_fabricatie|rafinarie|aviz_incarcare|quantity|
Livrari table
Id|masina_id|client_id|incarcare_id|deliver_quantity|aviz_livrare
Masini table
Id|numar_inmatriculare|marca|an_fabricatie|
Clienti table
Id|nume|localitate|date_add|date_upd|
SELECT c.id, c.nume, c.localitate, l.masina_id, i.nr_inmatriculare, i.an_fabricatie, i.rafinarie, m.marca, (SUM(i.quantity) + SUM(l.deliver_quantity)) AS total_quantity
FROM clienti c
INNER JOIN livrari l ON c.id = l.id
INNER JOIN incarcari i ON l.incarcare_id = i.livrari_id
INNER JOIN masini m ON i.id_marca = m.id
GROUP BY i.an_fabricatie, c.id, c.nume,c.localitate,l.masina_id, i.nr_inmatriculare, i.rafinarie, m.marca
HAVING i.quantity > 1000
ORDER BY m.marca DESC;
I have the following query, in which I used JOINs. It says:
unknown column m.bv ..
Could you please take a look and tell me what I'm doing wrong?
$query4 = 'SELECT u.*, SUM(c.ts) AS total_sum1, SUM(m.bv) AS total_sum
FROM users u
LEFT JOIN
(SELECT user_id ,SUM(points) AS ts FROM coupon GROUP BY user_id) c
ON u.user_id=c.user_id
LEFT JOIN
(SELECT user_id ,SUM(points) AS bv FROM matching GROUP BY user_id) r
ON u.user_id=m.user_id
where u.user_id="'.$_SESSION['user_name'].'"
GROUP BY u.user_id';
You are selecting SUM(points) AS bv from the table with the alias r, there is no tables with the alias m. So that it has to be r.bv instead like so:
SELECT
u.*,
SUM(c.ts) AS total_sum1,
SUM(r.bv) AS total_sum
FROM users u
LEFT JOIN
(
SELECT
user_id,
SUM(points) AS ts
FROM coupon
GROUP BY user_id
) c ON u.user_id=c.user_id
LEFT JOIN
(
SELECT
user_id,
SUM(points) AS bv
FROM matching
GROUP BY user_id
) r ON u.user_id = m.user_id
where u.user_id="'.$_SESSION['user_name'].'"
GROUP BY u.user_id
Replace m., with r. Look at second Join
You have aliased the derived table with r and you reference that table (twice) with m. Correct one or the other.
Since you group by user_id in the two subqueries and user_id is (I assume) the primary key of table user, you don't really need the final GROUP BY.
I would write it like this, if it was meant for all (many) users:
SELECT u.*, COALESCE(c.ts, 0) AS total_sum1, COALESCE(m.bv, 0) AS total_sum
FROM users u
LEFT JOIN
(SELECT user_id, SUM(points) AS ts FROM coupon GROUP BY user_id) c
ON u.user_id = c.user_id
LEFT JOIN
(SELECT user_id, SUM(points) AS bv FROM matching GROUP BY user_id) m
ON u.user_id = m.user_id
and like this in your (one user) case:
SELECT u.*, COALESCE(c.ts, 0) AS total_sum1, COALESCE(m.bv, 0) AS total_sum
FROM users u
LEFT JOIN
(SELECT SUM(points) AS ts FROM coupon
WHERE user_id = "'.$_SESSION['user_name'].'") c
ON TRUE
LEFT JOIN
(SELECT SUM(points) AS bv FROM matching
WHERE user_id = "'.$_SESSION['user_name'].'") m
ON TRUE
WHERE u.user_id = "'.$_SESSION['user_name'].'"
The last query can also be simplified to:
SELECT u.*,
COALESCE( (SELECT SUM(points) FROM coupon
WHERE user_id = u.user_id)
, 0) AS total_sum1,
COALESCE( (SELECT SUM(points) FROM matching
WHERE user_id = u.user_id)
, 0) AS total_sum
FROM users u
WHERE u.user_id = "'.$_SESSION['user_name'].'"
My query is
select COUNT(*) from result
where test_id in (select test_id
from test_schedule
where scheduler_id in (select user_id
from users
where user_type=1))
Try this:
SELECT COUNT(r.*)
FROM result r
INNER JOIN test_schedule s ON r.test_id = s.test_id
INNER JOIN users u ON s.scheduler_id = u.user_id
WHERE u.user_type = 1
SELECT COUNT(*)
FROM result r
JOIN (SELECT DISTINCT test_id
FROM test_schedule s
JOIN users u ON s.scheduler_id = u.user_id
WHERE u.user_type = 1) s
USING (test_id)
The DISTINCT is necessary to keep rows from being multiplied by all the rows in the other tables that match.
SELECT COUNT(r.*)
FROM result r
RIGHT JOIN test_schedule s USING(test_id)
RIGHT JOIN users u ON s.scheduler_id = u.user_id
WHERE u.user_type = 1
i have 2 table
users : id , name
order : id , price, user_id
a users have more than one order. And i want to select a users
who have total price >100 . how to do ?
EX : user John have 3 orders with price : 30$, 40$ , 50$
SELECT * FROM user u
INNER JOIN order o ON o.user_id = u.id
WHERE sum(o.price) >100
this query will get the user is john ? 30+40+50 = 110 >100
?
First of all you are not allowed to use aggregate functions (i.e. SUM) in your WHERE clause. They should be used in the HAVING clause. To compute aggregates you need to GROUP BY something, in your case by u.id.
So:
SELECT *
FROM user u
INNER JOIN order o ON u.user_id = u.id
GROUP BY u.id
HAVING sum(o.price) > 100
Note that if you would need users with no order you would have to use LEFT JOIN!
SELECT u.Id, Sum(o.price) FROM user u
INNER JOIN order o ON o.user_id = u.id
GROUP BY u.Id
HAVING sum(o.price) > 100
Thank for all answer but i catch problem
now i have a new table order_file
users : id , name
order : id , price, user_id
order_file : id , file , order_id
users, order is one-many
order , order_file is one-many
a user John have 1 order with price is 200$
and this order link to order_file with two record
SELECT *
FROM user u
INNER JOIN order o ON u.user_id = u.id
INNER JOIN order_file of ON of.order_id = o.id
WHERE u.name = 'John'
we will get two rows.Only diff value in order_file
now to get once i use DISTINCT , and i get 1 row
SELECT DISTINCT *
FROM user u
INNER JOIN order o ON u.user_id = u.id
INNER JOIN order_file of ON of.order_id = o.id
WHERE u.name = 'John'
then i do SUM , oh la la , i get 400$ , not 200$
SELECT DISTINCT *, sum(o.price)
FROM user u
INNER JOIN order o ON u.user_id = u.id
INNER JOIN order_file of ON of.order_id = o.id
WHERE u.name = 'John'
how to i can get extracty 200$ , not duplicate row :(