![](/img/trans.png)
[英]How to write an SQL command to input a column by using data from another column in the same table?
[英]How to write SQL to fetch the data of a column in another column
我有2个表tblA和tblB。 现在我想通过op_code获取名称。
tblA
op_code | date | num
------------------------------------------------
a | 03/01 | 34
b | 04/03 | 5556
c | 03/05 | 555
tblB
id | op_code | Name
------------------------------------------------
1 | a | Jet
2 | b,c | Mike
3 | d | Tom
由于tblB中的op_code数据是组合数据,所以我尝试编写如下的sql。
select a.*, b.*
from tblA a
LEFT JOIN tblB b on a.op_code in (SUBSTRING_INDEX(b.op_code, ',', 13))
它不起作用。 有什么建议吗?
你可以在这里使用FIND_IN_SET()
:
SELECT a.*, b.*
FROM tblA a
LEFT JOIN tblB b
ON FIND_IN_SET(a.op_code, b.op_code) > 0;
但是,由于在SQL表中存储CSV数据被视为不良做法,因为它是非标准化数据,因此您应该只查看临时解决方法查询。 一个更好的计划是承诺只为B表中的每个op_code
关系设置一条记录。
只是为了好玩,这是使用REGEXP
编写查询的另一种方法:
SELECT a.*, b.*
FROM tblA a
LEFT JOIN tblB b
ON b.op_code REGEXP CONCAT('[[:<:]]', a.op_code, '[[:>:]]');
以下是查询的第二个版本的演示:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.