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

inkz8wg9  于 2023-01-25  发布在  Mysql
关注(0)|答案(7)|浏览(184)

我有下面的表来存储用户数据:
例如:

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查询来比较表中的两行并查看哪些列不同?我不需要知道它们实际上有多大不同,只需要知道它们是否包含相同的值。另外,我将只比较选定的列,而不是用户表中的每一列。

hi3rlvi2

hi3rlvi21#

这将为用户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
c9x0cxw0

c9x0cxw02#

您还可以使用以下命令:

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

kmb7vmvb

kmb7vmvb3#

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

xwbd5t1u4#

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

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

o75abkj45#

我想,这可能会帮助一些人。查找同名的行并更新新记录和旧记录的日期。这可能是一个条件,您将不得不复制不同国家的新闻项目,并保持与原始日期相同。

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.标题集t2.创建= t.创建其中t.标题= t2.标题;

lstz6jyr

lstz6jyr6#

如果另一个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 |
+----------+-------+
    • 如果有一种方法能让所有人都这么做,那就太棒了**
hec6srdp

hec6srdp7#

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

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查询,您可以运行该查询来查看哪些列在两行之间具有不同的值。

相关问题