MySQL在子查询中加入

时间:2014-06-02 18:11:29

标签: mysql inner-join

我有这个:

# tab1 = Company
# tab2 = Forms
# tab3 = Filled forms from each company enabled to it.

# Search Companies with pending/empty Forms.
# Company #1 has 3 forms, all filled, not will be listed;
# Company #2 has form 2 and 3, only form 2 is filled, so it will be listed;
# Company #3 has not form filled, so it will be listed;

SELECT company.*
FROM tab1 as company

WHERE (
  SELECT TRUE
  FROM tab2 AS forms

  # Join compatible company forms results/fills.
  # Itll join with company.id (that here not exists) and the forms.id (that exists)
  LEFT JOIN tab3 AS fills ON
    fills.id_tab1 = company.id AND
    fills.id_tab2 = forms.id

  # Itll filter forms that company have.
  # And will accept ONLY if none result is found, what mean "pending fill" on company.
  # I need just that.
  WHERE 
    FIND_IN_SET(forms.id, company.id_forms) AND
    fills.id IS NULL
)

我得到未知专栏tab1.id
如何解决?

我需要访问SUBQUERY INNER内的tab1列。

更新#1 - 实时样本http://sqlfiddle.com/#!2/20aa5/3

1 个答案:

答案 0 :(得分:0)

试试这段代码,逻辑是一样的

 SELECT tab1.* from tab1
        inner join tab3 ON  tab3.id_tab1 = tab1.id
    WHERE .....