SELECT * FROM test t1
WHERE
t1.is_main = (
SELECT MAX(is_main) FROM test t2 WHERE t2.parent_id = t1.parent_id
)
OR NOT EXISTS(SELECT * FROM test t2 WHERE t2.parent_id = t1.parent_id AND t2.is_main IS NOT NULL)
GROUP BY t1.parent_id
SELECT DISTINCT t.nid, f.* FROM (
SELECT
id,
parentId,
isMain,
@nid := CASE
WHEN @parentId <> parentId
THEN id
ELSE @nid
END AS nid,
@parentId := parentId AS t2
FROM hfeed
ORDER BY parentID, isMain DESC
) AS t
INNER JOIN hfeed AS f ON f.id = t.nid
SELECT *, isMain IS NULL AS isnull FROM tablename ORDER BY isnull ASC GROUP BY parentId;
SELECT g.parentId, d.id, d.name, d.isMain FROM (SELECT DISTINCT parentId FROM my_table) g, JOIN my_table d ON d.id == ( SELECT o.id FROM my_table o WHERE o.parentId == g.parentId ORDER BY o.isMain DESC)
parentId
, но он у вас, наверное, есть. И вот это вот == (SELECT ...)
— это, наверное, особенность SQLite, там такая конструкция возвращает единственное значение. В другом диалекте может потребоваться писать что-то вроде:ON d.id IN ( SELECT o.id FROM my_table o WHERE o.parentId == g.parentId ORDER BY o.isMain DESC LIMIT 1)
Select id, ParentId, name, isMain
FROM dbo.Cash
where isMain is not null
UNION ALL
SELECT x.*
FROM dbo. x
inner join
(
Select ParentId, MIN(id) as id
FROM dbo.Cash
where parentId not in (Select ParentId FROM dbo.Cash where isMain is not null)
group by ParentId
) y
on x.id = y.id
order by 2