简体   繁体   English

MySQL - 根据包含 where 子句的另一个列值选择特定列

[英]MySQL - select specific columns based on another column value with where clause included

I would be forever in debt to the one person that can help me with this case / issue that I'm having:我将永远欠下一个可以帮助我解决我遇到的这个案例/问题的人的债务:

There is a table with the following structure:有一个具有以下结构的表:

id(AI)| ColA | ColB   | ColC
-----------------------------
1     |1     | lorem  | ipsum
2     |1     | dolor  | sit
3     |0     | amet   | nula
...

I would like to set the columns to search in (ColB or ColC) based on the value in the ColA.我想根据 ColA 中的值设置要在(ColB 或 ColC)中搜索的列。 For example (pseudo query):例如(伪查询):

  • select * from table if ColA = 1 then ColB like '%some_criteria%' else if ColA = 0 then (ColB like '%some_criteria%' and ColC like '%some_criteria%') select * from table if ColA = 1 then ColB like '%some_criteria%' else if ColA = 0 then (ColB like '%some_criteria%' and ColC like '%some_criteria%')

Basically, in the same one query:基本上,在同一个查询中:

  • if ColA has value '1' then search only in ColB如果 ColA 的值为“1”,则仅在 ColB 中搜索
  • if ColA has value '0' then search in ColB and ColC如果 ColA 的值为“0”,则在 ColB 和 ColC 中搜索

Let's say that ColB stores article titles and ColC stores articles descriptions.假设 ColB 存储文章标题,ColC 存储文章描述。 ColA stores articles types. ColA 存储文章类型。 So, if article type is 1, search only in title else, if article type is 0 then search in title and description.因此,如果文章类型为 1,则仅在标题中搜索,如果文章类型为 0,则在标题和描述中搜索。

Thank you in advance for your help!预先感谢您的帮助!

You could do it with conditions in the WHERE clause SQL Switch/Case in 'where' clause您可以使用WHERE子句中的条件来实现SQL Switch/Case in 'where' 子句

SELECT *
FROM table
WHERE 
    (ColA = 1 AND ColB LIKE '%some_criteria%')
    OR
    (ColA = 0 AND (ColB LIKE '%some_criteria%' OR ColC LIKE '%some_criteria%'))

Also, a simple UNION would work as another example https://www.w3schools.com/sql/sql_union.asp此外,一个简单的UNION可以作为另一个例子https://www.w3schools.com/sql/sql_union.asp

SELECT *
FROM table
WHERE ColA = 1 AND ColB LIKE '%some_criteria%'
UNION ALL
SELECT *
FROM table
WHERE ColA = 0 AND (ColB LIKE '%some_criteria%' OR ColC LIKE '%some_criteria%')

Note that UNION ALL would return duplicates if any were to occur, and just UNION returns distinct rows.请注意,如果出现重复项, UNION ALL将返回重复项,并且仅UNION返回不同的行。

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

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