繁体   English   中英

SQL 比较表中的两行,找出有多少值不同

[英]SQL compare two rows in a table to find how many values are different

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

例如

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

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

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

例如

    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 查询是否有更短的方法,我可以在其中比较表中的两行并查看哪些列不同? 我不需要知道它们实际上有多少不同,只需要知道它们是否包含相同的值。 此外,我只会比较选定的列,而不是用户表中的每一列。

这将选择用户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

你也可以用这个:

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

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

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

这是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}!";

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

 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 ttt on t.title = t2.title set t2.created = t.created其中t.title = t2.title;

如果另一个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 |
+----------+-------+

如果有一种方法可以集体进行,那将是太棒了。

如果要找出表的两行中哪些列的值不同,可以使用以下查询:

SET @table_name = 'YOUR_TABLE_NAME';
SET @primary_column_name = 'PRIMARY_COLUMN_NAME';
SET @row1_id = '1234';
SET @row2_id = '1111';


SELECT CONCAT(
    "SELECT ",
    (
        SELECT GROUP_CONCAT(" (CASE WHEN t1.", column_name, " != t2.", column_name ," THEN t1.", column_name, " ELSE '-' END) AS ", column_name ,"\n") AS all_column_names 
                FROM information_schema.columns WHERE table_name = @table_name AND table_schema = DATABASE()
    ), " FROM ",@table_name," AS t1 INNER JOIN Artiklar AS t2 ON(t1.",@primary_column_name," = '",@row1_id,"' AND t2.",@primary_column_name," = '",@row2_id,"')
    UNION ALL
    SELECT ",
    (
        SELECT GROUP_CONCAT(" (CASE WHEN t1.", column_name, " != t2.", column_name ," THEN t2.", column_name, " ELSE '-' END) AS ", column_name ,"\n") AS all_column_names 
                FROM information_schema.columns WHERE table_name = @table_name AND table_schema = DATABASE()
    ), " FROM ",@table_name," AS t1 INNER JOIN Artiklar AS t2 ON(t1.",@primary_column_name," = '",@row1_id,"' AND t2.",@primary_column_name," = '",@row2_id,"')
") 

它将为您提供一个新的 SQL 查询,您可以运行该查询以查看哪些列在两行之间具有不同的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM