gpt4 book ai didi

mysql - 如何使用MySQL语句选择重复记录并保留数据?

转载 作者:行者123 更新时间:2023-11-29 08:09:55 25 4
gpt4 key购买 nike

例如,我的表 categories是这样的:

categories_id                    categories_name
---------------------- --------------------
1 aaa
2 bbb
3 ccc
5 ddd
9 eee

我使用以下语句来保留重复记录。但重复的记录不会出现。

SELECT categories_id, categories_name 
FROM categories
WHERE categories_name in ("aaa","bbb","bbb","ccc","ccc","ddd","ddd","ddd")
ORDER BY categories_name

我想获取这样的记录:

categories_id                    categories_name
---------------------- --------------------
1 aaa
2 bbb
2 bbb
3 ccc
3 ccc
5 ddd
5 ddd
5 ddd

有人可以帮助我吗?

最佳答案

以下代码给出所需的输出:

SELECT Tab1.categories_id, Tab1.categories_name
FROM categories AS Tab1
RIGHT JOIN
(
SELECT "aaa" AS categories_name
UNION ALL
SELECT "bbb"
UNION ALL
SELECT "bbb"
UNION ALL
SELECT "ccc"
UNION ALL
SELECT "ccc"
UNION ALL
SELECT "ddd"
UNION ALL
SELECT "ddd"
UNION ALL
SELECT "ddd"
) AS Tab2
ON Tab1.categories_name = Tab2.categories_name
ORDER BY Tab1.categories_name;

SQL Fiddle .

关于mysql - 如何使用MySQL语句选择重复记录并保留数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21832373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com