简体   繁体   English

如何在另一个查询的LIKE条件下使用SQL查询结果?

[英]How can an SQL query result be used in the LIKE condition of another query?

I have created a subquery that searches for a particular string from one table, using the SQL LIKE condition. 我创建了一个子查询,使用SQL LIKE条件从一个表中搜索特定字符串。 I would like to use this subquery's result as the string to search for in my main SQL query also using the LIKE condition. 我想将此子查询的结果作为字符串使用LIKE条件在我的主SQL查询中进行搜索。 I tried the below code but I get syntax errors, although it seems to be the way it should be done...sadly I am not an SQL expert and just trying to feel this out. 我尝试了下面的代码,但出现语法错误,尽管这似乎是应该这样做的方法……不幸的是,我不是SQL专家,只是想尝试一下。

SELECT * FROM `allcesseries` 
WHERE series_id LIKE '%'+(SELECT industry_code FROM `ceindustry` WHERE industry_name LIKE '%Technical and trade schools%')+'%'
SELECT * FROM `allcesseries` 
WHERE series_id LIKE concat('%',
    (SELECT industry_code FROM `ceindustry` 
    WHERE industry_name LIKE '%Technical and trade schools%'),
'%')

I would suggest that you use exists in this case: 我建议您在这种情况下使用exists

SELECT *
FROM `allcesseries` a
WHERE EXISTS (SELECT 1 
              FROM `ceindustry` c
              WHERE c.industry_name LIKE '%Technical and trade schools%' AND
                    a.series_id LIKE CONCAT('%', c.industry_code, '%') 
             );

If you have multiple matches, then this will work as expected. 如果您有多个匹配项,则它将按预期工作。

You can also phrase this directly as a join, if you want: 如果需要,也可以直接将其作为联接短语:

SELECT a.*
FROM `allcesseries` a JOIN
     ceindustry c
     ON c.industry_name LIKE '%Technical and trade schools%' AND
        a.series_id LIKE CONCAT('%', c.industry_code, '%')

But if there are multiple rows that satisfy the conditions in ceindustry , you will get duplicates. 但是,如果有多行满足ceindustry的条件,您将得到重复的行。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM