简体   繁体   English

如何从同一个表的两列查询等于一个值

[英]How to query from two column of a same table where equal to one value

I have a mysql table as follow 我有一个mysql表如下

id|  reagent1  | reagent 2
1 |  coffee    |  milk
2 |  sugar     |  coffee
3 |  coffee    |  salt

If I would like to get the reagents of coffee, the result should be 如果我想得到咖啡的试剂,结果应该是

reagentofcoffee
milk
sugar
salt

How can I make a query to get expected result? 如何进行查询以获得预期结果? I am new to mysql and I have tried many time. 我是mysql的新手,我已经尝试了很多次。

You can use case : 你可以使用case

select case when reagent1 = 'coffee' then reagent2 
            when reagent2 = 'coffee' then reagent1 end as reagentofcoffee
from tbl
SELECT IF(reagent1 = 'coffee',reagent1,reagent2) as reagent FROM table WHERE reagent1 = 'coffee' OR reagent2 = 'coffee'

A case expression in the select list should do the trick: select列表中的case表达式应该可以解决问题:

SELECT CASE reagent1 WHEN 'coffee' THEN reagent2 ELSE reagent1 END
           AS reagentofcoffee
FROM   reagents
WHERE  'coffee' IN (reagent1, reagent2)

暂无
暂无

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

相关问题 我如何在MySQL中查询两个日期,其中datefrom在同一表的第二列中? - How do I query two dates in mysql where the datefrom is in one column and dateto is in the second column of the same table? 如何将两列的组合值复制到同一表中的一列 - How to copy the combined value of two column to one Column in same table sql连接中存在相同名称的两列时,如何从一个表列获取值 - How to get value from one table column when two columns of the same name exist in an sql join 从表中获取列值不等于零的值 - get the values from table where the column value is not equal to zero 如何使来自同一表的两个$ db-> query具有按列彼此独立地位于一个php页面中的两个不同ORDER? - How to make two $db->query from the same table with two different ORDER by column that each other stand independenty in one php page? 如何从总和(特定列值)等于输入值的表中查询结果列表 - How to query result list from a table that sum(it's specific column value) equal an input value SQL查询以从一个表中获取数据,其中特定列等于另一表中的值 - SQL Query to get data from one table where a specific column equals value from other table 如何从两个表中插入一个表中的值等于另一个表中的值的值? - how to insert values from two tables with value in one table is equal to value in the other? 如何从sql表中获取列值等于同一sql表的列值的最大计数的行 - how to get a row from sql table which have a column value equal to maximum of count of a column value of same sql table 仅当使用MySQL在一个表中的列值与另一表相同时,才如何从两个表返回数据? - How to return data from two tables only when the column value in one table is same as another table using MySQL?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM