我有一个看起来像这样的数据库。
x 2 3 4 5
4 8 12 16 20
5 10 15 20 25
6 12 18 24 30
7 14 21 28 35
当最终用户插入一个值时,我想将x变量与x列中的值匹配,将另一个变量与数值列名称匹配。
那么我将如何编写一个执行此操作的SQL查询呢?
SELECT * FROM times_tables WHERE x=4 and COLUMN_NAME=4;
谢谢:)
答案 0 :(得分:3)
SELECT
`4`
FROM
(SELECT
4 as `x`, 8 as `2`, 12 as `3`, 16 as `4`, 20 as `5`
UNION ALL
SELECT 5, 10, 15, 20, 25
UNION ALL
SELECT 6, 12, 18, 24, 30
UNION ALL
SELECT 7, 14, 21, 28, 35) `times_tables`
WHERE
`x` = 4
输出:
4
---
16
因此,在您的情况下,查询可能是这样的:
SELECT `{$col}` FROM `times_tables` WHERE `x` = {$row};
<强> UPD:强>
可以使用纯SQL完成:
SET @r = 4; -- row
SET @c = 5; -- col
SET @qry = CONCAT('SELECT `', @c ,'` FROM `times_tables` WHERE `x` = ', @r);
PREPARE stmt FROM @qry;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
P.S。:您可以将SQL包装到存储过程中以获得更好的保护。