I like to use the result from another query to address the column name. For this I like to use CONCAT()
. But somehow it don't work; when I run this line I get 0 rows back:
SELECT * FROM cover WHERE CONCAT('c','9') = 1;
When I don't make use of CONCAT()
it work perfectly:
SELECT * FROM cover WHERE c9 = 1;
And also CONCAT()
seems to work. With this I get a result:
SELECT CONCAT('c','9');
I tried all solution from this question: MySQL select with CONCAT condition
like this one, but i always got 0rows back:
SELECT * FROM (
SELECT id, CONCAT('c', '9') as target
FROM cover) base
WHERE target = "1"
My MySQL Version is; 10.1.16-MariaDB
It is bad schema design to splay an array across a bunch of columns. And, as you are discovering, it is hard to use the columns. Build another table for the c
values.
Or...
With lots of 0/1 "columns", consider SET
or BIGINT UNSIGNED
; either will hold up to 64 boolean flags in a tiny fraction of the space. And, with different code, BLOB
could be used.
To extract bit 22 from a BIGINT
, ((col >> 22) & 1)
will give you 0 or 1.
Consider using a case when
, since the number of options is known beforehand (you can only access columns that exist):
SELECT id
FROM cover
WHERE case ?
when 1 then c1
when 2 then c2
when 9 then c9
end = 1
... where the question mark would be the provided value, like 9 in your example.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.