php - 如果 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;
但这似乎是一个糟糕的选择,因为当涉及许多变量时,它的行为很奇怪。
解决方案
假设您希望将结果放在一行中,请执行两个SELECT
s 并从每个中选择结果:
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 代码必须检查每一行的height
or age
:
if ( $row['field_1'] == 'age' ) {
// $row['field_2'] is the age
} else if ( $row['field_2' == 'height' ) {
// $row['field_2'] is the height
}
推荐阅读
- python - 将列表的元素与子列表的元素进行比较python
- react-native - react-native 从 lon lat 获取地址不显示
- android - 如何更改按下按钮颤动的总数
- javascript - React componentDidMount 没有触发
- plugins - 通过 RDF4J API 配置/启用 GeoSPARQL 插件
- python - 如何添加 django admin 只读权限?
- javascript - 加载图像后加载音频不起作用
- java - 来自下载链接的 Javafx 图像
- cookies - $.cookie 不是 Liferay DXP 中的函数错误
- python - 通过 Python 2.7 重启远程 ubuntu 服务器