php - 动态where子句mysql php

标签 php mysql dynamic-sql

我这里有一个问题..我有1个动态表..我想问你一个问题,是否可以根据我的动态表创建一个where子句..让我解释一下..

这是我的 table

标签属性

_____________________
idAttribute | Name
_____________________
1           | Width
2           | Diameter
3           | AR
etc

是否可以仅基于该表创建自动/动态 where 子句。名称值

width = ? AND Diameter = ? AND AR = ? AND etc

有什么建议吗?

让我进一步解释一下..

假设我有一个包含我的条件的变量 $query...

$query = "SELECT * FROM xxx WHERE ".$where;

不..在我的 $where 变量中,如果我正常编写它,根据上面的表格,它将是..

$where = "width = ? AND diameter = ? AND AR = ?";

我的问题是如何根据上面的表格创建 $where 动态,所以如果我上面的表格是

idAttribute | Name
__________________
1           | Width
2           | Diameter
3           | AR
4           | Weight

会自动变成这样

$where = "width = ? AND diameter = ? AND AR = ? AND weight = ?";

有什么建议吗?

最佳答案

由于您没有提供太多详细信息,因此不清楚您要问什么。我根据您详细说明的一张表格做了一些假设。如果您希望查询基于 name 值的数据,您可以使用如下内容:

select i.name i_name,
  a.name a_name,
  ia.value
from item i
left join item_attribute ia
  on i.itemid = ia.itemid
left join attribute a
  on ia.idattribute = a.idattribute
where a.name = 'Width'
  and ia.value = 100

参见SQL Fiddle with Demo

但是,通过首先将数据转换为列,然后进行搜索,查询数据可能会更容易,类似于:

select *
from
(
  select i.name i_name,
    sum(case when a.name = 'Width' then ia.value end) width,
    sum(case when a.name = 'Diameter' then ia.value end) diameter,
    sum(case when a.name = 'AR' then ia.value end) ar,
    sum(case when a.name = 'Weight' then ia.value end) weight
  from item i
  left join item_attribute ia
    on i.itemid = ia.itemid
  left join attribute a
    on ia.idattribute = a.idattribute
  group by i.name
) src
where width = 100

参见SQL Fiddle with Demo

关于php - 动态where子句mysql php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13236007/

相关文章:

php - 阅读网站页面

php - Ajax /PHP : Updating a Database

mysql - 使用 group by 子查询进行多行更新的 SQL (mysql) 查询解释

php - mysql连接查询没有得到正确的输出

mysql 返回一小时的订单量,在列日期

php - 验证用户是否被禁止 PHP?

MySQL 查询删除位于 ExpressionEngine 中的三个表中的 200,000 个垃圾邮件成员

sql - 使用查询结果设置下一个查询的表

SQL Server : How to write and execute a prepared statement?

php - 从表格收集的数据不完整