考虑这张表:( http://sqlfiddle.com/#!9/dd313a/4由@Michael Berkowski提供))
CREATE TABLE transactions (
idTransactions INT,
idMemberCard INT,
amountFinal FLOAT,
idAccount INT,
dateTransaction DATETIME
);
INSERT INTO `transactions` (`idTransactions`, `idMemberCard`, `amountFinal`, `idAccount`, `dateTransaction`) VALUES
(131532, 64924, 20.00, 292, '2015-07-22 10:59:53'),
(131533, 64924, -5.00, 292, '2015-07-22 11:00:03'),
(131534, 64925, 12.00, 292, '2015-07-22 11:01:07'),
(131535, 64925, -3.00, 292, '2015-07-22 11:01:13'),
(131539, 64926, 80.00, 292, '2015-07-22 11:03:06'),
(131540, 64926, 12.50, 292, '2015-07-22 11:03:18'),
(131541, 64926, -4.90, 292, '2015-07-22 11:03:31'),
(131542, 64927, 37.50, 291, '2015-07-22 11:04:28'),
(131543, 64927, -4.50, 291, '2015-07-22 11:04:35'),
(131544, 64928, 18.00, 291, '2015-02-22 11:05:03'),
(131545, 64928, -5.00, 291, '2015-03-22 11:05:09'),
(131546, 64929, 5.00, 291, '2015-01-22 11:05:51'),
(131547, 64929, 10.00, 291, '2015-02-22 11:05:55'),
(131548, 64929, 3.00, 291, '2015-03-22 11:06:00'),
(131549, 64929, -2.50, 291, '2015-04-22 11:06:05'),
(131550, 64926, -4.50, 291, '2015-07-22 11:07:38'),
(131551, 64925, -2.30, 291, '2015-07-22 11:08:48'),
(131564, 64928, 15.00, 293, '2015-05-22 11:12:14'),
(131566, 64928, -6.50, 293, '2015-07-22 11:12:20'),
(131567, 64929, -5.40, 293, '2015-05-22 11:12:51'),
(131568, 64929, 1.90, 293, '2015-06-22 11:12:57');
我想选择仅 <{1}}和idMemberCard
在此示例中, 131532 和 131533 将排除,因为这对64924和292彼此链接并且相互关联#34;仅在这两行中。
不同的是, 131534 和 131535 和 131551 应选择,因为 64925 涉及 292 *和** 291 帐户
换句话说,我想选择所有相关的行&#34; idMemberCard&#34;和&#34; idAccount&#34;在不同的(非唯一的)idAccounts中,因此不包括&#34; idMemberCard&#34;和&#34; idAccount&#34;与其他人只有直接关系且没有其他历史相关性的对#id; idAccount&#34;
查询的预期输出:
idAccount
答案 0 :(得分:0)
如果我已正确理解要求,则以下内容应该有效:
SELECT t.*
FROM transactions t
JOIN (SELECT idMemberCard
FROM transactions
GROUP BY idMemberCard
HAVING COUNT(DISTINCT idAccount) > 1) g
ON t.idMemberCard = g.idMemberCard
SQLFiddle here。
使用WHERE EXISTS也可以进行等效查询,但我认为这个版本在MySQL中表现更好。