如果 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数据。


我正在查询SELECTand GROUP BY id,但接下来我该做什么?


我试过这个方法:


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

    $height = $row['field_2'];

endif;

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


慕后森
浏览 111回答 2
2回答

红糖糍粑

假设您想要一行中的结果,请执行两次SELECT并从每个中选择结果: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}

慕丝7291255

尝试这个$arr = [];$height;$width;$q = "SELECT `field_2` FROM `table_Nam` WHERE `id` = 3";$result = mysqli_fetch_assoc(mysqli_query($con, $q));while($row = $result){    if($row['field_1'] ==     'height')      {   $height = $row['field_2'];    }else if($row[field_2'] ==     'age'){      $age = $row['field_2'];    }} 希望这可以帮助
打开App,查看更多内容
随时随地看视频慕课网APP