mysql 表格多个字段同时乘以某一个值,使用MySQL将值与表中的多个列(在一条语句中)匹配...

这篇博客讨论了如何在MySQL中使用PreparedStatement来动态构建查询语句,特别是当需要根据多列值进行筛选时。通过设置SQL语句并结合INFORMATION_SCHEMA.COLUMNS表,可以构建一个查询所有列值等于1的表达式,而无需手动输入每个列名。这种方法适用于存储过程,以避免硬编码列名。
摘要由CSDN通过智能技术生成

I'm working with a table in MySQL that contains the following columns:

id, january, february, march, april, etc

The data in the table looks like this:

aa, 0, 0, 1, 0

ab, 1, 0, 1, 0

ac, 1, 1, 0, 0

ad, 1, 1, 1, 0

To query it, I could easily do this:

select * from table where january = 1 and february = 1

The result would be:

ac, 1, 1, 0, 0

ad, 1, 1, 1, 0

I want to know if there's a way to do it like this:

select * from table where table.columns = 1

I want to use table columns in expression without actually specifying the names manually (typing them out).

Bonus (+1) question:

Could it be done using Match/Against like this:

select * from table

where

(

match (somehow,get,the,table,columns,I,need,here)

against (1 in boolean mode)

)

Thanks for your time! :)

解决方案

You have to use a Prepared Statement, because what you want to do can only be done with dynamic SQL:

SET @stmt = 'SELECT * FROM YOUR_TABLE WHERE 1 = 1 '

SET @stmt = CONCAT(@stmt, (SELECT CONCAT_WS(' AND ', CONCAT(column_name, ' = 1 '))

FROM INFORMATION_SCHEMA.COLUMNS

WHERE table_name = 'YOUR_TABLE'

AND table_schema = 'db_name'

AND column_name NOT IN ('id')));

PREPARE stmt FROM @stmt;

EXECUTE stmt;

DEALLOCATE PREPARE stmt;

The first SET statement constructs a basic SELECT statement; the "1 = 1" portion is just there to make it easier to concatenate the "AND column = 1"

The second SET statement concatenates the contents of the query to get the list of columns based on the table name onto the end of the string in the first SET statement. The idea is that this:

SELECT CONCAT_WS(' AND ', CONCAT(column_name, ' = 1 '))

FROM INFORMATION_SCHEMA.COLUMNS

WHERE table_name = 'YOUR_TABLE'

AND table_schema = 'db_name'

AND column_name NOT IN ('id')

... will return a row that resembles "AND january = 1 AND february = 1 ...". You'd have to update the NOT IN clause if there are other columns you don't want in the WHERE clause.

The rest is just standard prepared statement stuff, and this all would have to take place within a stored procedure.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值