[英]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):例如(伪查询):
Basically, in the same one query:基本上,在同一个查询中:
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.