我的表:
id | title_en | value
--------------------------
1 | t1 | 1000
2 | t1 | 2000
3 | t1 | 3000
4 | t2 | 4000
5 | t2 | 5000
6 | t2 | 6000
我想在他们的ID中获取他们的行:
2,3(对于title_en = t1)
和
5,6(对于title_en = t2)
这是我的代码,但它不起作用:
SELECT * FROM table GROUP BY `title_en` HAVING COUNT(`title_en`) > 2
提前感谢。
答案 0 :(得分:1)
这很棘手,特别是在MySQL中。我相信以下是你想要的:
select t.*
from t
where t.id >= (select t2.id
from t t2
where t2.title_en = t.title_en
order by t2.id desc
limit 1 offset 1
);
MySQL对limit
子句中子查询中where
的使用非常挑剔。标量子查询通常是可以的 - 一个最多返回一行的子查询。
答案 1 :(得分:1)
一种解决方案是使用GROUP_CONCAT。 将GROUP_CONCAT生成的隐藏逗号分隔值与UNION ALL一起生成的行与SUBSTRING_INDEX(SUBSTRING_INDEX(ids,',',1),',', - 1)组合以获取id。 你需要在你的桌子上加入那个id。
警告这种方式使用GROUP_CONCAT是一种hacky。您可能还想更改group_concat_max_len lenght,因为默认值为1024位。 随着
SET SESSION group_concat_max_len = val;
<强>查询强>
SELECT
Table1.*
FROM (
SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX(ids, ',', 1), ',', -1) as id
FROM (
SELECT
*
FROM (
SELECT
title_en
, GROUP_CONCAT(id ORDER BY id DESC) ids
FROM
Table1
GROUP BY
title_en
ORDER BY
title_en ASC
)
AS
title1_ids
)
AS
row1
UNION ALL
SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX(ids, ',', 2), ',', -1) as id
FROM (
SELECT
*
FROM (
SELECT
title_en
, GROUP_CONCAT(id ORDER BY id DESC) ids
FROM
Table1
GROUP BY
title_en
ORDER BY
title_en ASC
)
AS
title1_ids
)
AS
row2
)
as rows
INNER JOIN
Table1
ON
rows.id = Table1.id
ORDER BY
rows.id ASC
<强>结果强>
| id | title_en | value |
|----|----------|-------|
| 2 | t1 | 2000 |
| 3 | t1 | 3000 |
| 5 | t2 | 5000 |
| 6 | t2 | 6000 |
demo http://sqlfiddle.com/#!9/73377/31
第二个解决方案是找到每个title_en的第二个最后MAX值。 然后加入你的桌子。
<强>查询强>
SELECT
Table1.*
FROM (
SELECT
MAX(id) as id
, title_en
FROM
Table1
WHERE
id NOT IN (
SELECT
MAX(id) as id
FROM
Table1
GROUP BY
title_en
)
GROUP BY
Table1.title_en
)
AS Table1_second_last_max
INNER JOIN
Table1
ON
Table1.id >= Table1_second_last_max.id
AND
Table1.title_en = Table1_second_last_max.title_en
ORDER BY
Table1.id
<强>结果强>
| id | title_en | value |
|----|----------|-------|
| 2 | t1 | 2000 |
| 3 | t1 | 3000 |
| 5 | t2 | 5000 |
| 6 | t2 | 6000 |
答案 2 :(得分:0)
对于重复的行 您可以使用not in for subselect来检索每个title_en
的oldes id select * from my_table
inner join (
select id from my_table
where (id, title_en ) in not in (
select min(id), title_en
from my_table
group by title_en
)
group by title_en
having count(*) > 1 ) t on t.id = my_table.id