SQL比较表中的两行以查找有多少值不同

时间:2012-05-08 06:38:15

标签: mysql sql

我有下表用于存储用户数据:

e.g。

TABLE: users
COLUMNS:
...
maritalStatus (INT)   - FK
gender        (CHAR)
occupation    (INT)   - FK
...

现在我要比较此表中的两个用户,看看有多少列匹配任何两个给定用户(比如用户X和用户Y)

我是通过mySQL存储过程实现的,分别获取每个值然后比较它们

e.g。

    SELECT maritalStatus from users where userID = X INTO myVar1;
    SELECT maritalStatus from users where userID = Y INTO myVar2;

    IF myVar1 = myVar2 THEN

    ...

    END IF;

使用SQL查询是否有更短的方法,我可以比较表中的两行并查看 哪些列不同?我不需要知道他们实际上有多么不同,只是 需要知道它们是否包含相同的值。另外我只会比较选定的列, 不是用户表中的每一列。

6 个答案:

答案 0 :(得分:10)

这将为用户x和用户y选择相同的列数:

SELECT ( u1.martialStatus <> u2.martialStatus )
     + ( u1.gender        <> u2.gender        )
     + ( u1.occupation    <> u2.occupation    )
FROM
  users u1,
  users u2
WHERE u1.id = x
  AND u2.id = y

答案 1 :(得分:2)

您也可以使用:

select 

   -- add other columns as needed
   (a.lastname,a.gender) 
=  (b.lastname,a.gender) as similar,


  a.lastname as a_lastname,
  a.firstname as a_firstname,
  a.age as a_age,

  'x' as x,

  b.lastname as b_lastname,
  b.firstname as b_firstname,
  b.age as b_age



from person a
cross join person b
where a.id = 1 and b.id = 2

输出:

SIMILAR A_LASTNAME A_FIRSTNAME A_AGE X B_LASTNAME B_FIRSTNAME B_AGE
1       Lennon     John        40    x Lennon     Julian      15

实时测试:http://www.sqlfiddle.com/#!2/840a1/2

答案 2 :(得分:0)

您可以使用group by计算具有相同列的用户数:

select  u1.maritalStatus
,       u1.gender
,       u1.occupation
,       count(*)
from    users u1
group by
        u1.maritalStatus
,       u1.gender
,       u1.occupation

答案 3 :(得分:0)

这是Peter Langs在PHP中建议的一个例子:

$arr_cols   = array('martialStatus', 'gender', 'occupation');
$arr_where = array();
$arr_select = array();
foreach($arr_cols as $h) {

    $arr_having[] = "compare_{$h}";
    $arr_select[] = "(u1.{$h} != u2.{$h}) AS compare_{$h}";

}

$str_having  = implode(' + ', $arr_where);
$str_select = implode(', ', $arr_where);

$query = mysql_query("
SELECT {$str_select}
FROM users AS u1, users AS u2
WHERE u1.userid = {$int_userid_1} AND u2.userid = {$int_userid_2}
HAVING {$str_having} > 0
");

/* Having case can be removed if you need the row regardless. */

/* Afterwards you check these values: */

$row = mysql_fetch_assoc($query);
foreach($arr_cols as $h)
    if ($row["compare_{$h}"])
         echo "Found difference in column {$h}!";

答案 4 :(得分:0)

我想,这可能对某人有所帮助。 目标:查找具有相同名称的行并使用旧记录更新新记录日期。这可能是您必须为不同国家/地区复制新闻项目并与原始日期保持相同日期的条件。

CREATE TABLE `t` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `locale` varchar(10) DEFAULT 'en',
  `title` varchar(255) DEFAULT NULL,
  `slug` varchar(255) DEFAULT NULL,
  `body` text,
  `image` varchar(255) DEFAULT NULL,
  `thumb` varchar(255) DEFAULT NULL,
  `slug_title` varchar(255) DEFAULT NULL,
  `excerpt` text,
  `meta_title` varchar(200) DEFAULT NULL,
  `meta_description` varchar(160) DEFAULT NULL,
  `other_meta_tags` text,
  `read_count` int(10) DEFAULT '0',
  `status` varchar(20) DEFAULT NULL,
  `revised` text,
  `created` datetime DEFAULT NULL,
  `modified` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8;


INSERT INTO `t` (`id`, `locale`, `title`, `slug`, `body`, `image`, `thumb`, `slug_title`, `excerpt`, `meta_title`, `meta_description`, `other_meta_tags`, `read_count`, `status`, `revised`, `created`, `modified`)
VALUES
	(2, 'en', 'A title once again', '/news/title-one-again', 'And the article body follows.', '/uploads/2014/11/telecommunications100x100.jpg', NULL, NULL, NULL, '', '', NULL, 0, 'Draft', NULL, '2014-09-22 12:26:17', '2014-10-23 10:13:21'),
	(3, 'en', 'A title once again', '/news/title-strikes-back', 'This is really exciting! Not.', '/uploads/2014/11/telecommunications100x100.jpg', NULL, NULL, NULL, '', '', NULL, 0, 'Unpublished', NULL, '2014-09-23 12:26:17', '2014-10-31 11:12:55'),
	(4, 'en_GB', 'test', '/news/test', 'test', '/uploads/2014/11/telecommunications100x100.jpg', NULL, NULL, NULL, '', '', NULL, 0, 'Published', NULL, '2014-10-23 10:14:30', '2014-10-23 10:14:30');


update t join
       t t2
       on t.title = t2.title 
    set t2.created = t.created
    where t.title = t2.title ;

更新t加入        t t2        在t.title = t2.title     set t2.created = t.created     其中t.title = t2.title;

答案 5 :(得分:0)

如果另一个Magento开发人员在这里找到他们的方式,此Q / A的特定用途是比较表中的两个地址条目。 “Magento 1”会将相同的地址设置为两次,唯一的区别是关键entity_id列和address_type列(结算或送货)。

已经知道订单entity_id,请使用此功能获取与订单相关联的结算和送货地址ID:
SELECT entity_id FROM sales_flat_order_address WHERE parent_id = 3137;

然后看看他们的订单是否有所不同:

SELECT a1.parent_id AS 'order_id'
,  ( a1.street    <> a2.street    )
 + ( a1.city      <> a2.city      )
 + ( a1.postcode  <> a2.postcode  )
 + ( a1.region_id <> a2.region_id )
 AS 'diffs'
FROM
  sales_flat_order_address a1,
  sales_flat_order_address a2
WHERE a1.entity_id = 6273
  AND a2.entity_id = 6274
;

给出输出:

+----------+-------+
| order_id | diffs |
+----------+-------+
|     3137 |     0 |
+----------+-------+

如果有一种方法可以大规模地进行,那将是非常棒的。