[英]How to compare two column from different table and differentiate in mysql?
[英]How to compare two different row of a table in Mysql
我有一張桌子,上面有列
ID標簽值
表中的值是這樣的
1 ac.id 12345
1 ac.title xyz
2 ac.id 12345
2. ac.title Yo its the title
在這種情況下,我想比較具有相同標簽的兩個不同ID的值,如果值不同,則更新較小的ID
例如
ac.title的值在id 2和1中是不同的,所以我將用2更新1的值。
提前致謝
http://sqlfiddle.com/#!9/40f442/1
UPDATE table1
INNER JOIN (
SELECT *
FROM table1) t
ON t.tag=table1.tag
AND t.val != table1.val
AND t.id > table1.id
SET table1.val = t.val
答案仍然是使用聯接,但是它是這樣的:
update test t1
left join test t2
on t1.id < t2.id
and t1.name = t2.name
set t1.value = t2.value
where t2.id is not null;
如果有幾行帶有相同標簽但ID不同的行,則可能需要運行多次。 如果那是一個重要的問題,請發表評論,然后我將提出不同的查詢-這只是快速簡便的解決方案。
編輯
這是稍微復雜但更有效的解決方案。 這樣會將ID較低的所有標簽更新為ID為MAX的標簽值。
update test t1
inner join
(
select q1.*, t2.value from
(
select max(id) id, name
from test
group by name
) q1
inner join test t2
on q1.id = t2.id
and q1.name = t2.name
) m
on t1.name = m.name
and t1.id < m.id
set t1.value = m.value
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.