将嵌套sql SELECT语句中的SELECT结果分配给变量 - PHP

时间:2014-12-23 07:42:08

标签: php mysql sql nested-queries

在PHP-MySQL中,我使用嵌套的select语句,如下所示:

SELECT object_id FROM form_entry WHERE id=(SELECT entry_id FROM form_entry_values WHERE value='32711178-888' AND field_id = (SELECT id FROM form_field WHERE name='dealer'))

每个SELECT仅返回一个单元格。但是,我需要这些SELECT的每个结果,例如我需要(深度3):

SELECT id FROM oform_field WHERE name='dealer'

我也需要(深度2):

SELECT entry_id FROM form_entry_values WHERE value='32711178-888' AND field_id = (SELECT id FROM form_field WHERE name='dealer')

我需要(深度1):

SELECT object_id FROM form_entry WHERE id=(SELECT entry_id FROM form_entry_values WHERE value='32711178-888' AND field_id = (SELECT id FROM form_field WHERE name='dealer'))

有没有办法在最大的SQL查询的一次执行期间分配这些语句的结果(表示为"深度1和#34;)?换句话说,如果不执行三个sql查询,我正在寻找一种方法,将每个深度的SELECT语句结果分配给$ result_1,$ result_2等变量。

听起来没有办法处理它,但提前谢谢......

2 个答案:

答案 0 :(得分:3)

您的查询等同于:

SELECT e.object_id
FROM form_entry e
  INNER JOIN form_entry_values v ON e.id=v.entry_id
  INNER JOIN form_field f ON v.field_id = f.id
WHERE v.value='32711178-888' 
  AND f.name='dealer'

并且在此表单中答案很简单:只需将v.entry_idf.id添加到SELECT子句中的表达式列表中:

SELECT e.object_id, v.entry_id, f.id
FROM form_entry e
  INNER JOIN form_entry_values v ON e.id=v.entry_id
  INNER JOIN form_field f ON v.field_id = f.id
WHERE v.value='32711178-888' 
  AND f.name='dealer'

答案 1 :(得分:3)

尝试类似:

SELECT depth1.object_id, depth2.entry_id, depth3.id
FROM form_entry depth1
JOIN form_entry_values depth2 ON depth1.id=depth2.entry_id
JOIN form_field depth3 ON depth3.id=depth2.entry_id
WHERE
depth2.value='32711178-888'
AND depth3.name='dealer';