This question already has an answer here:
SQL statement is ignoring where parameter
(1 answer)
Closed 5 years ago.
I have a query which uses BETWEEN for showing the records between two dates. My query needs to show records whose arrival_date and departure_date between specific dates. But query somehow shows all records.
Column types are DATE.
SELECT DISTINCT art.* FROM accommodation_room_types art
INNER JOIN accommodation_rooms ar ON art.id = ar.room_type
INNER JOIN accommodation a ON art.accommodation = a.id
WHERE a.id = 13 AND NOT EXISTS
(
SELECT 1 FROM booked_rooms br INNER JOIN booking b ON br.booking = b.id
WHERE br.room = ar.id
AND
(
b.arrival_date BETWEEN '2017-12-16' AND '2018-04-16'
)
OR
(
b.departure_date BETWEEN '2017-12-16' AND '2018-04-16'
)
)
Even I write BETWEEN 'asd' AND 'asd', it still shows all records and doesn't give any format error.
Is my query wrong for showing records between two specific dates?
I don't know if your logic is right or wrong, but your syntax is not doing what you intend. I would suggest:
WHERE a.id = 13 AND
NOT EXISTS (SELECT 1
FROM booked_rooms br INNER JOIN
booking b
ON br.booking = b.id
WHERE br.room = ar.id AND
(b.arrival_date BETWEEN '2017-12-16' AND '2018-04-16' OR
b.departure_date BETWEEN '2017-12-16' AND '2018-04-16'
)
)
It strikes me that all that empty space in the query makes it hard to see that your logic was written as: A AND B OR C. Your intention (presumably) is A AND (B OR C).
Substitute 1 for *
The way you wrote query, it always return 1, regardless of conditions. Moreover, that is totally legit.
Related
This question already has answers here:
Can you use an alias in the WHERE clause in mysql?
(5 answers)
Closed 3 years ago.
I have multiple tables with data on some clients. What I want to achieve is to output the amount that a certain client was billed for, in the first month he was billed.
So I run the code similar to the one bellow:
SELECT company,clientid,COALESCE (signed.value,reactivated.value) as 'Activation' , Amount FROM `tblclients`
LEFT JOIN tblcustomfieldsvalues as signed ON tblclients.clientid = signed.relid and signed.fieldid = 5
LEFT JOIN tblcustomfieldsvalues as reactivated ON tblclients.userid = reactivated.relid and reactivated.fieldid = 27
LEFT JOIN (
SELECT clientid,sum(total) as Amount FROM tblinvoices
WHERE month(invoicedate)=month(Activation) Group by clientid) as f on tblclients.clientid = f.clientid
My problem is that when I do the last join it gives an error : Unknown column 'Activation' in 'where clause'.
If I switch that to current_date the rest of the query works.
Any idea on how to make this work ?
Later edit: I might have oversimplified the query, I also have a COALESCE
You can try below -
SELECT company,clientid,activated.value as Activation , Amount
FROM `tblclients`LEFT JOIN tblcustomfieldsvalues as signed ON tblclients.clientid = signed.relid and signed.fieldid = 5
LEFT JOIN
( SELECT clientid,sum(total) as Amount
FROM tblinvoices Group by clientid
) as f on tblclients.clientid = f.clientid and month(invoicedate)=month(Activation)
my table user contains these fields
id,company_id,created_by,name,image
table valet contains
id,vid,dept_id
table cart contains
id,dept_id,map_id,purchase,time
to get the details i have written this mysql query
SELECT c.id, a.id, c.purchace, c.time
FROM user a
LEFT JOIN valet b ON a.vid = b.id
AND a.is_deleted = 0
LEFT JOIN cart c ON b.dept_id = c.dept_id
WHERE a.company_id = 18
AND a.created_by = 102
AND a.is_deleted = 0
AND c.time
IN ( SELECT MAX( time ) FROM cart WHERE dept_id = b.dept_id )
from these three table i want to select last updated raw from cart along with id from user table which is mapped in valet table
this query works fine but it takes almost 15 sec to retrieve the details .
is there any way to improve this query or may be i am doing some wrong.
any help would be appreciated
For one thing, I can see that you’re running the subquery for each row. Depending on what the optimiser does, that may have an impact. max is a pretty expensive operation (there’s nothing for it but to read every row).
If you plan to update and use this query repeatedly, perhaps you should at least index the table on cart.time. This will make it much easier to find the maximum value.
MySQL has the concept of user variables, so you can set a variable to the result of the subquery, and that might help:
SELECT c.id, a.id, c.purchace, c.time
FROM
user a
LEFT JOIN valet b ON a.vid = b.id AND a.is_deleted = '0'
LEFT JOIN cart c ON b.dept_id = c.dept_id
LEFT JOIN (SELECT dept_id,max(time) as mx FROM cart GROUP BY dept_id) m on m.dept_id=c.dept_id
WHERE
a.company_id = '18'
AND a.created_by = '102'
AND a.is_deleted = '0'
AND c.time=m.mx;
Note also:
since you’re only testing a single value (max) for c.time, you should be using = not in.
I’m not sure about is why you are using strings instead of integers. I shold have though that leaving off the quotes makes more sense.
Your JOIN includes AND a.is_deleted = '0', though you make no mention of it in your table description. In any case, why is it in the JOIN and not in the WHERE clause?
I am working on a query with the following format:
I require all the columns from the Database 'A', while I only require the summed amount (sum(amount)) from the Database 'B'.
SELECT A.*, sum(B.CURTRXAM) as 'Current Transaction Amt'
FROM A
LEFT JOIN C
ON A.Schedule_Number = C.Schedule_Number
LEFT JOIN B
ON A.DOCNUMBR = B.DOCNUMBR
ON A.CUSTNMBR = B.CUSTNMBR
GROUP BY A
ORDER BY A.CUSTNMBR
My question is regarding the grouping statement, database A has about 12 columns and to group by each individually is tedious, is there a cleaner way to do this such as:
GROUP BY A
I am not sure if a simpler way exists as I am new to SQL, I have previously investigated GROUPING_ID statements but thats about it.
Any help on lumped methods of grouping would be helpful
Since the docnumber is the primary key - just use the following SQL:
SELECT A.*, sum(B.CURTRXAM) as 'Current Transaction Amt'
FROM A
LEFT JOIN C
ON A.Schedule_Number = C.Schedule_Number
LEFT JOIN B
ON A.DOCNUMBR = B.DOCNUMBR
ORDER BY RM20401.CUSTNMBR
GROUP BY A.DOCNUMBR
I'm having a problem regarding a query because i don't have all the records and i don't know why
This is the query
SELECT `ebspma_paad_ebspma`.`semana_dias`.`dia`,`ebspma_paad_ebspma`.`req_material_sala`.`sala`, `ebspma_paad_ebspma`.`req_material_tempo`.`inicio`, `ebspma_paad_ebspma`.`sala_ocupacao`.`id_ocup`, `ebspma_paad_ebspma`.`turmas`.`turma`
FROM `ebspma_paad_ebspma`.`sala_ocupacao`
INNER JOIN `ebspma_paad_ebspma`.`semana_dias`
ON (`sala_ocupacao`.`id_dia` = `semana_dias`.`id_dia`)
INNER JOIN `ebspma_paad_ebspma`.`req_material_sala`
ON (`sala_ocupacao`.`id_sala` = `req_material_sala`.`idsala`)
LEFT JOIN `ebspma_paad_ebspma`.`req_material_tempo`
ON (`sala_ocupacao`.`id_tempo` = `req_material_tempo`.`idtempo`)
LEFT JOIN `ebspma_paad_ebspma`.`turmas`
ON (`sala_ocupacao`.`id_turma` = `turmas`.`id_turma`)
where`ebspma_paad_ebspma`.`sala_ocupacao`.`id_turma` = '$turma'
GROUP BY `ebspma_paad_ebspma`.`sala_ocupacao`.`id_dia` , `ebspma_paad_ebspma`.`req_material_tempo`.`inicio` ASC";
Running this query i have almost records but this is a school timetable and when a class is divided in 2 groups i have two classrooms for this class. With this query i have only one group
For exemple the class start at 1 PM in two classrooms (27 and 31), with this query i should have at 1 PM the classroom X is on 27 and 31 classroom, but i have only the first one
Image to check http://postimg.org/image/u24r35fkz/
And my database image http://postimg.org/image/hyvpb1qz1/ce7a7320/
So what's wrong with my query?
Thanks
UPDATE 1
I have simplified my query to
SELECT t2.`dia` , t3.`sala` , t4.`inicio` , t1.`id_ocup` , t5.`turma`
FROM `ebspma_paad_ebspma`.`sala_ocupacao` AS t1
INNER JOIN `ebspma_paad_ebspma`.`semana_dias` AS t2 ON ( t1.`id_dia` = t2.`id_dia` )
INNER JOIN `ebspma_paad_ebspma`.`req_material_sala` AS t3 ON ( t1.`id_sala` = t3.`idsala` )
LEFT JOIN `ebspma_paad_ebspma`.`req_material_tempo` AS t4 ON ( t1.`id_tempo` = t4.`idtempo` )
LEFT JOIN `ebspma_paad_ebspma`.`turmas` AS t5 ON ( t1.`id_turma` = t5.`id_turma` )
WHERE t1.`id_turma` =12
GROUP BY t1.`id_dia` , t3.`idsala` , t4.`inicio`
Now i can see all the classes but not in the right order, the order should be given by t4.inicio and by day (id dia)
You are not grouping by sala so MySQL will behave badly and give you a random row that fits the other requirements. Better functioning database engines would give you an error saying you haven't aggregated or grouped all result columns.
If you add sala to GROUP BY you should see the difference.
For the ordering: you're not asking the database to ORDER BY anything so the rows will be in whatever order they happen to come out. Probably want to add ORDER BY t4.inicio, t1.id_dia to handle that.
This question already has answers here:
MySQL query, MAX() + GROUP BY
(7 answers)
Closed 9 years ago.
I'm trying to write a query that will pull out the "best" record from a list of values:
SELECT s.swimmerName, r.resultTimeText, r.resultAgeGroup, r.resultEventID, v.venueName
FROM tblResults r
JOIN tblEvents e ON e.eventID = r.resultEventID
JOIN tblSwimmers s ON r.resultSwimmerID = s.swimmerID
JOIN tblVenues v ON e.resultVenueID = v.venueID
WHERE s.swimmerGender = %s
AND r.resultStroke = %s
GROUP BY s.swimmerName
This selects all of my records but people are listed twice with different times (a consequence of the DISTINCT I know). What would be the best way to select the best time for each person?
You can use mysql's quirky grouping to help you:
SELECT * FROM (
SELECT s.swimmerName, r.resultTimeText, r.resultAgeGroup, r.resultEventID, v.venueName
FROM tblResults r
JOIN tblEvents e ON e.eventID = r.resultEventID
JOIN tblSwimmers s ON r.resultSwimmerID = s.swimmerID
JOIN tblVenues v ON e.resultVenueID = v.venueID
WHERE s.swimmerGender = %s
AND r.resultStroke = %s
ORDER BY 2) x
GROUP BY swimmerName
ORDER BY 2
This works by first ordering the data fastest to slowest, then grouping by name. In myswl (only) grouping by not all non-aggregated columns has the effect of filtering only the first row encountered for each unique combination of grouped by colums.