Need assistance with SQL statement for below condition. Have 3 columns in a table (TableName), Sno (unique records), Name ( there are multiple records that can have same name) , Condition (True,False) . Need to extract All records if the last record true only.
Have tried below query
select Sno(Max),Name,Condition
from TableName
where Conditon = 'True'
group by Name,Conditon;
Expected: If last record (SNo (Max)) has value = true (condition column) then return this record, else no records displayed.
Actual: All records are displayed including true and false condition
I think you're looking for that:
SELECT Sno, Name, Condition
FROM TableName
WHERE Conditon = 'True' AND Sno=(SELECT MAX(Sno) FROM TableName);
Beware of types: if 'Condition' column is Boolean
WHERE clause should be
WHERE Condition IS TRUE AND ...
I think this is what you are looking for.
If table is like this:
[It's recommended to use tinyint(1)
as Boolean in MySQL.]
You can use this query:
SELECT a.*
FROM `TableName` a
LEFT JOIN `TableName` b ON(a.`Sno` < b.`Sno`
AND a.`Name` = b.`Name`)
WHERE a.`Conditon` = 1
AND b.`Sno` IS NULL
This way will work more effective than using an inner sub-query. Especially in large tables.
Could be use a where exist on a subquery for condition TRUE and Sno = max(Sno)
select *
from TableName
where exist (
select *
from TableName
where Condition = 'True'
and Sno = (
select max(Sno)
from TableName
)
)
SELECT *
FROM tablename
WHERE sno IN (SELECT Sno(max)
FROM tablename
GROUP BY NAME)
AND condition = 'true'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.