首页 > 解决方案 > 如果 field_1 包含 %word% 使用 MySQL 和 PHP 返回 field_2

问题描述

我有一个数据库,不幸的是,它恰好是这样填充的:

id       field_1       field_2
-------- ------------- -------
1        weight        175
1        height        88
1        age           26
2        weight        166
2        age           15
3        weight        84
3        height        188
3        age           44

假设我想从 id 3获取height和数据。age

我正在SELECT查询 and GROUP BY id,但接下来我该怎么做?

我试过这个方法:

if (strpos( $row['field_1'], 'height') !== false) :
    $height = $row['field_2'];
endif;

但这似乎是一个糟糕的选择,因为当涉及许多变量时,它的行为很奇怪。

标签: phpmysql

解决方案


假设您希望将结果放在一行中,请执行两个SELECTs 并从每个中选择结果:

SELECT height, age FROM (
  ( SELECT `field_2` AS height FROM tbl WHERE `id`=1 AND `field_1`='height') t1,
  ( SELECT `field_2` AS age FROM tbl WHERE `id`=1 AND `field_1`='age') t2
)

或者,如果您不介意解析结果:

SELECT * FROM `tbl` WHERE id=3 AND ( field_1='height' OR field_2='age' )

然后你的 PHP 代码必须检查每一行的heightor age

if ( $row['field_1'] == 'age' ) {
    // $row['field_2'] is the age
} else if ( $row['field_2' == 'height' ) {
    // $row['field_2'] is the height
}

推荐阅读