MYSQL LEFT 使用“LIKE”连接
我正在尝试加入两个表。问题是其中一个表的单元格内实际上有一个以逗号分隔的列表。我需要加入“csv 单元格”。使用我的基于沙拉的示例,我希望培根与培根,火鸡一起加入,并给我一个cobb_salad
SELECT tbl_a.item, tbl_b.item, tbl_b.salad
FROM tbl_a
LEFT JOIN tbl_b
ON tbl_a.item LIKE CONCAT('%', tbl_b.item, '%')
我尝试了上面的示例和其他一些变体。我意识到这不会是一个有效的查询。问题是底层数据集早于我。幸运的是,我只需要运行查询一次。
Expected Result
+--------+------------+
| item | salad |
+--------+------------|
| ham | chef_salad |
| bacon | cobb_salad |
| turkey | cobb_salad |
+---------------------+
tbl_a
+------+
| item |
+------+
|bacon |
| ham |
|turkey|
+------+
tbl_b
+--------------+------------+
| item | salad |
+--------------+------------+
| ham | chef_salad |
| bacon,turkey | cobb_salad |
+--------------|------------+
I am trying to join two tables. The issue is one of the tables actually has a comma-separated list inside the cell. I need to join on the 'csv cell.' Using my salad based example I want bacon to join with bacon,turkey and give me a cobb_salad
SELECT tbl_a.item, tbl_b.item, tbl_b.salad
FROM tbl_a
LEFT JOIN tbl_b
ON tbl_a.item LIKE CONCAT('%', tbl_b.item, '%')
I tried the example above and a few other varations. I realize this is not going to be an efficent query. The issue is that the underlying dataset predates me. Luckily I only need to run the query once.
Expected Result
+--------+------------+
| item | salad |
+--------+------------|
| ham | chef_salad |
| bacon | cobb_salad |
| turkey | cobb_salad |
+---------------------+
tbl_a
+------+
| item |
+------+
|bacon |
| ham |
|turkey|
+------+
tbl_b
+--------------+------------+
| item | salad |
+--------------+------------+
| ham | chef_salad |
| bacon,turkey | cobb_salad |
+--------------|------------+
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
注意:
我在您的数据库中显示,您的表中有许多
空格字符
。请在插入数据库之前尝试修剪它。
例如:
来自:
火腿
=>[空格]火腿[空格]
致:
火腿
=>[无空格]火腿[无空格]
希望你明白我说的话。
您可以尝试:
它对我有用:
更新:
这是我的表格:
并且
NOTICE:
I show in your db, there are many
space characters
in your tables.Please try to trim it before inserting into your db.
Ex:
From:
ham
=>[space]ham[space]
To:
ham
=>[no-space]ham[no-space]
Hope you understand what I said.
You can try:
It works for me:
UPDATE:
Here is my tables:
AND