Compare values of two columns

孤者浪人 提交于 2020-01-15 22:12:10

问题


Is there a way to compare the values of two columns in MySQL? For example if I have a table:

+----------------+
| Col1  | Col2   |
|----------------|
| abc   | 123abc |
| def   | 234def |
|       | 123ghi |
+----------------+

And I wanted to retrieve all the entries in Col2 that contained the values of Col1:

+---------+
| NewCol  |
|---------|
| 123abc  |
| 234def  | 
+---------+

How would I go about that?

Here is a pseudo-query to explain a bit further.

SELECT Col2 FROM TableName WHERE Col2 LIKE Col1;

回答1:


Use LOCATE()

WHERE LOCATE(Col1, Col2);

It returns a non-zero value if Col1 is contained within Col2.

Update

Note that an empty substring is always contained within another string, so in this case you need another condition:

WHERE LENGTH(Col1) AND LOCATE(Col1, Col2);



回答2:


SELECT Col2 FROM TableName WHERE Col2 in(SELECT Col1 from TableName);



回答3:


SELECT Col2 FROM TableName WHERE Col2 LIKE Concat("%",Col1,"%");


来源:https://stackoverflow.com/questions/22601073/compare-values-of-two-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!