简体   繁体   English

根据另一个表的“相似”值从一个表中检索记录

[英]Retrieving records from one table based in 'similar' values of another table

I'm trying to come up with a select syntax for retrieving records from one table (B) based in 'similar' values of another unrelated table (A). 我试图提出一种选择语法,用于根据另一个不相关表(A)的“相似”值从一个表(B)检索记录。

There are two tables: 有两个表:

TABLE_A
ID  CODE    COMPANY
1   234     XYZ Corporation, LLC
2   142     Corp ABC Enterprise, S.L.D.
3   145     Z. Incorporated, GmBH
4   134     XYZ Corporation, LLC
5   741     Z. Incorporated, GmBH
6   952     Corp ABC Enterprise, S.L.D.

TABLE_B
ID  COMPANY
1   XYZ Corporation
2   Z. Incorporated
3   Corp ABC Enterprise
4   Just another Company

I need to extract TABLE_B.COMPANY field from criteria existing in TABLE_A. 我需要从TABLE_A中存在的条件中提取TABLE_B.COMPANY字段。 For example, if search criteria is CODE=234, I need the result ' XYZ Corporation ' from TABLE_B. 例如,如果搜索条件为CODE = 234,则需要TABLE_B的结果“ XYZ Corporation ”。

TABLE_A has repeated companies, whereas TABLE_B has not. TABLE_A有重复的公司,而TABLE_B没有。

So far I have this: 到目前为止,我有这个:

SELECT DISTINCT T1.COMPANY
FROM TABLE_A T1 WHERE EXISTS
(SELECT 1 FROM 
(SELECT CONCAT(T2.COMPANY, '%') AS Company FROM TABLE_B T2) c 
WHERE T1.COMPANY LIKE Company AND T1.CODE='234';

This yields the result ' XYZ Corporation, LLC ' whereas I need ' XYZ Corporation '. 这将产生结果“ XYZ Corporation,LLC ”,而我需要“ XYZ Corporation ”。 That is, I need something like SELECT T2.COMPANY FROM ... which obviously does not work because that variable is unknown for the first SELECT. 也就是说,我需要像SELECT T2.COMPANY FROM ...这样的东西,它显然不起作用,因为第一个SELECT未知该变量。

Thanks! 谢谢!

You need a join instead of exists to get the row from table_b : 你需要一个join ,而不是exists于从获取该行table_b

SELECT DISTINCT T2.COMPANY
FROM TABLE_A T1 JOIN
     TABLE_B T2
     ON T1.COMPANY LIKE CONCAT(T2.COMPANY, '%') AND T1.CODE = '234'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何根据另一个表中的值删除一个表中的记录? - How to delete records in one table based on the values in another table? MYSQL根据另一个表的几个不同值从一个表中选择5条记录 - MYSQL Select 5 records from one table based on several different values from another 根据另一个表中的不存在从一个表中删除记录 - Removing records from one table based on lack of presence in another CakePHP:根据另一个表中的值过滤对一个表的搜索 - CakePHP: Filter search on one table based on values from another table 根据另一个表列中的值过滤一个表 - Filter one table based on values from another table column 根据另一个表的值更新一个表的列值 - Update column value of one table based on values from another table 从另一个表中选择一个不同的值 - Select different values from one table based on another table 根据一个表中的不同值和另一表中的不同值查找记录 - Finding records based off distinct values in one table and different values in another table 根据另一个表中的值从一个表中选择多个值 - Select multiple values from one table based on values in another 对另一个相似表中具有匹配值的记录进行分组,计数和排除 - Group, count, and exclude records with matching values in another similar table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM