假设我有以下customer_offer
表。
我的问题是:
如何选择 键 在该表中重复的所有行?
+---------+-------------+------------+----------+--------+---------------------+
| link_id | customer_id | partner_id | offer_id | key | date_updated |
+---------+-------------+------------+----------+--------+---------------------+
| 1 | 99 | 11 | 14 | mmmmmq | 2011-09-21 12:40:46 |
| 2 | 100 | 11 | 14 | qmmmmq | 2011-09-21 12:40:46 |
| 3 | 101 | 11 | 14 | 8mmmmq | 2011-09-21 12:40:46 |
| 4 | 99 | 11 | 14 | Dmmmmq | 2011-09-21 12:59:28 |
| 5 | 100 | 11 | 14 | Nmmmmq | 2011-09-21 12:59:28 |
+---------+-------------+------------+----------+--------+---------------------+
非常感谢您的回答。有很多答案都很好。现在我得到了解决方案。
答案 0 :(得分:3)
select *
from customer_offer
where key in
(select key from customer_offer group by key having count(*) > 1)
<强>更新强> 正如@ Scorpi0所提到的,如果使用大表,最好使用join。从mysql6.0开始,新的优化器会将这种子查询转换为连接。
答案 1 :(得分:1)
Self join
SELECT * FROM customer_offer c1 inner join customer_offer c2
on c1.key = c2.key
或group by
字段然后在count > 1
SELECT COUNT(key),link_id FROM customer_offer c1
group by key, link_id
having COUNT(Key) > 1
答案 2 :(得分:1)
SELECT DISTINCT c1.*
FROM customer_offer c1
INNER JOIN customer_offer c2
ON c1.key = c2.key
AND c1.link_id != c2.link_id
假设link_id
是主键。
答案 3 :(得分:0)
mysql网站上有许多线程解释了如何执行此操作。此链接将解释如何使用mysql执行此操作:http://forums.mysql.com/read.php?10,180556,180567#msg-180567
作为一个简短的例子,下面的代码来自链接,略有修改,更适合您的示例。
SELECT *
FROM tbl
GROUP BY key
HAVING COUNT(key)>1;
您还可以使用我喜欢的方法的joing,因为这会删除较慢的count方法:
SELECT *
FROM this_table t
inner join this_table t1 on t.key = t1.key
答案 4 :(得分:0)
使用子查询进行计数检查,使用主查询选择行。计数检查查询只是:
SELECT `link_id` FROM `customer_offer` GROUP BY `key` HAVING COUNT(`key`) > 1
然后外部查询将通过加入它来使用它:
SELECT customer_offer.* FROM customer_offer
INNER JOIN (SELECT `link_id` FROM `customer_offer` GROUP BY `key` HAVING COUNT(`key`) > 1) AS count_check
ON customer_offer.link_id = count_check.link_id
答案 5 :(得分:0)
SELECT link_id, key, count(key) as Occurrences
FROM table
GROUP BY key
HAVING COUNT(key)>1;