0

我有一个看起来像这样的数据库。

 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;

谢谢 :)

4

1 回答 1

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};

升级版:

可以用纯 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;

PS:您可以将 SQL 包装到存储过程中以获得更好的保护。

于 2013-04-17T04:00:07.107 回答