M
M
max_rip2011-11-30 16:28:42
SQL
max_rip, 2011-11-30 16:28:42

SQL query how?

There is a table
id|parentId|name|isMain
1|1|a1|null
2|1|a2|null
3|1|a3|null
4|2|b1|null
5|2|b2|1
6|2|b3| null
8|3|c1|1
9|3|c2|null
It is necessary to select records so that from each parentId group there is only one line GROP BY copes with this, but so that if the group has isMain 1, then it is displayed, if not, then any corresponding group.
In general, the output should be something from the series
1|1|a1|null
5|2|b2|1
8|3|c1|1

Answer the question

In order to leave comments, you need to log in

6 answer(s)
M
m00t, 2011-11-30
@max_rip

Option 1 - in the forehead. Formally works correctly (unlike the first two answers), but ugly:
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

E
edogs, 2011-11-30
@edogs

select id, parentid, name, max(ismain) as max_ismain from tablename group by parentid;

I
Ivan Komarov, 2011-12-01
@FreeTibet

Wrote for fun trying to emulate T-SQL ROW_NUMBER on MySQL:


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

E
Evengard, 2011-11-30
@Evengard

Try ka
SELECT *, isMain IS NULL AS isnull FROM tablename ORDER BY isnull ASC GROUP BY parentId;

M
MikhailEdoshin, 2011-11-30
@MikhailEdoshin

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)

You need an index on parentId, but you probably have it. And here it is == (SELECT ...)- this is probably a feature of SQLite, where such a construction returns a single value. In another dialect, you may need to write something like:
    ON d.id IN (
       SELECT o.id
         FROM my_table o
        WHERE o.parentId == g.parentId
     ORDER BY o.isMain DESC
        LIMIT 1)

A
Acristi, 2011-11-30
@Acristi

Is this an option that might work?
Arrange indexes and perhaps optimize something else ...
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

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question