我必须返回比较两个表时不同的所有行/行数。
我发现除了在sql中。在mysql中是否有任何东西像mysql中的except或intersect?
我知道可以使用列表中包含列名的查询来完成,但我不想使用列名。
我的例子
|column1|column2|column3|column4|column5|column6|
+-------+-------+-------+-------+-------+-------+
|Value 1|Value 2|Value 3|Value 4|Value 5|Value 6|
|Value 1|Value 2|Value 3|Value 4|Value 5|Value 6|
|Value 1|Value 2|Value 3|Value 4|Value 5|Value 6|
|Value 1|Value 2|Value 3|Value 4|Value 5|Value 6|
|Value 1|Value 2|Value 3|Value 4|Value 5|Value 6|
|column1|column2|column3|column4|column5|column6|
+-------+-------+-------+-------+-------+-------+
|Value 1|Value 2|Value 3|Value 4|Value 5|Value 6|
|Value 1|Value 2|Value 3|Value 4|Value 5|Value 6|
|Value 1|Value 2|Value 3|Value 4|Value 5|Value 6|
|Value 1|Value 2|Value 3|Value 4|Value 5|Value 6|
|Value 1|Value 2|Value 3|Value 4|Value 5|Value 6|
只能使用表名吗?
由于
答案 0 :(得分:2)
由于没有已知的列名称,您可以使用NATURAL LEFT JOIN
:
SELECT t1.*
FROM table1 t1
NATURAL LEFT JOIN (SELECT t2.*, 1 AS some_magic_name FROM table2 t2) t2
WHERE t2.some_magic_name IS NULL
UNION
SELECT t2.*
FROM table2 t2
NATURAL LEFT JOIN (SELECT t1.*, 1 AS some_magic_name FROM table1 t1) t1
WHERE t1.some_magic_name IS NULL
答案 1 :(得分:1)
是的,您可以通过基于该方案构建两个查询来实现这一点,然后将它们组合在一起..分组所有字段和条件计数(*)到1.这里的一个简单示例(完整的sql):
set @tablea='tablea';
set @tableb='tableb';
SELECT
CONCAT(
"SELECT ",
GROUP_CONCAT(CONCAT('`', column_name, '` as f',ordinal_position) ORDER BY column_name),
" FROM `",
@tablea,
"`"
)
FROM `information_schema`.`columns`
WHERE `table_schema`=DATABASE()
AND `table_name`=@tablea
INTO @querya;
SELECT
CONCAT(
"SELECT ",
GROUP_CONCAT(CONCAT('`', column_name, '` as f',ordinal_position) ORDER BY column_name),
" FROM `",
@tableb,
"`"
)
FROM `information_schema`.`columns`
WHERE `table_schema`=DATABASE()
AND `table_name`=@tableb
INTO @queryb;
SELECT
GROUP_CONCAT(CONCAT('`tbl`.`f',ordinal_position,'`') ORDER BY column_name)
FROM `information_schema`.`columns`
WHERE `table_schema`=DATABASE()
AND `table_name`=@tablea
INTO @groupbypart;
select concat('select * from ((',@querya,')UNION ALL(',@queryb,')) as tbl group by ',@groupbypart,' having count(*) =1')
into @finalquery;
PREPARE execquery FROM @finalquery;
EXECUTE execquery;