Mysql 如何从mysq中的表1中减去表2?
我正在寻找一种简单的方法,从另一个表中减去一个表中存在的值。MySQl的某种减号运算符 通过代码删除它们、循环第一个表、删除与第二个表匹配的行将是我的最后一个选择,因为我简化了我的问题,但它要复杂得多 请注意,复杂性在于重复的行。没有唯一字段,必须保留每个重复的行 例如: 给定一个以任意给定顺序排列字母的表格,a写5次,B写3次:Mysql 如何从mysq中的表1中减去表2?,mysql,subtraction,Mysql,Subtraction,我正在寻找一种简单的方法,从另一个表中减去一个表中存在的值。MySQl的某种减号运算符 通过代码删除它们、循环第一个表、删除与第二个表匹配的行将是我的最后一个选择,因为我简化了我的问题,但它要复杂得多 请注意,复杂性在于重复的行。没有唯一字段,必须保留每个重复的行 例如: 给定一个以任意给定顺序排列字母的表格,a写5次,B写3次: Table1 +--+ |ID| +--+ |A | |A | |A | |B | |A | |B | |B | |A | +--+ 和另一个字母相同
Table1
+--+
|ID|
+--+
|A |
|A |
|A |
|B |
|A |
|B |
|B |
|A |
+--+
和另一个字母相同的表,A出现两次,B出现一次
Table2
+--+
|ID|
+--+
|A |
|A |
|B |
+--+
所需的输出将是:
A在第一个表中出现5次,在第二个表中出现2次,这意味着输出中有3行。
B在第一个表中出现3次,在第二个表中出现1次,因此,结果将是2行
谢谢你你可以试试这个:
select id from (
select id,concat(id,
case when id = @id then @rownum := @rownum+1 else @rownum:=1 end) as x,
@id:=id
from table1 inner join(select @rownum :=1,@id:='') n
) as t where x not in(
select x from(
select concat(id,
case when id = @id then @rownum := @rownum+1 else @rownum:=1 end) as x,
@id:=id
from table2 inner join(select @rownum :=1,@id:='') n2
) t2)
我们需要使用行号使列唯一。由于mysql不支持rownum作为oracle,我们需要变量@rownum,@id来生成Rownumer。然后表1应该是这样的:A1,A2,A3和表2。因此,我们可以通过查询得到类似于表2中where id not inid的结果。下面的查询将为您提供所需的输出。在这里,我们计算ID的数量,在从表1中选择期间,保持一个计数以仅显示表2中已计数的项目数:
select id from (
select id,concat(id,
case when id = @id then @rownum := @rownum+1 else @rownum:=1 end) as x,
@id:=id
from table1 inner join(select @rownum :=1,@id:='') n
) as t where x not in(
select x from(
select concat(id,
case when id = @id then @rownum := @rownum+1 else @rownum:=1 end) as x,
@id:=id
from table2 inner join(select @rownum :=1,@id:='') n2
) t2)
SELECT
id
FROM
(SELECT
*,
IF(@prevvalue <> id, @counter:=0, @counter),
IF(@counter < counter, @counter:=@counter + 1, NULL) shouldshow,
@prevvalue:=id
FROM
(SELECT
table1.*, table2.id t2id, table2.counter
FROM
table1
JOIN (SELECT
COUNT(id) counter, id
FROM
table2
GROUP BY id) table2 ON (table1.id = table2.id)
ORDER BY table1.id) table1, (SELECT @counter:=0, @prevvalue:=NULL) countertable) table1
WHERE
shouldshow IS NULL
ORDER BY id;