如果子类别包含数据,则选择顶级类别

时间:2015-05-04 15:28:01

标签: sql doctrine-orm

我基本上有一个表 hebergement_type ,其中包含以下数据:

╔══════════════════╦══════════════════╦══════════════════╦═══════════════════╗   
║     category     ║   sub_category   ║      label       ║ hebergement_count ║   
╠══════════════════╬══════════════════╬══════════════════╬═══════════════════╣   
║ main             ║                  ║ Immo             ║                 5 ║   
║ main             ║                  ║ Hotel            ║                 5 ║   
║ main             ║ chambre-vacances ║ Appart + Studios ║                   ║   
║ chambre-vacances ║                  ║ Appart Vacances  ║                 2 ║   
║ chambre-vacances ║                  ║ Studios          ║                 3 ║   
╚══════════════════╩══════════════════╩══════════════════╩═══════════════════╝   

返回immo,hotel:

SELECT hebergement_type.label hebergement_type.id FROM hebergement
JOIN hebergement_type ON hebergement.hebergement_type = hebergement_type.id
WHERE hebergement_type.category = 'main'

返回immo,hotel,appart vacances,studios:

SELECT DISTINCT hebergement_type.label, hebergement_type.id FROM hebergement
JOIN hebergement_type ON hebergement.hebergement_type = hebergement_type.id
LEFT JOIN hebergement_type as ht ON ht.sub_category = hebergement_type.category
WHERE ht.category = 'main' OR hebergement_type.category = 'main'

但是我们需要返回:immo,hotel,appart + studios - >作为回报,所有匹配'main'类型的类别都不是空的,如果有sub_category,请检查sub_category项目。

DDL for hebergement

CREATE TABLE hebergement (id INTEGER NOT NULL, hebergement_type INTEGER DEFAULT NULL, name VARCHAR(128) DEFAULT NULL, PRIMARY KEY(id), CONSTRAINT FK_4852DD9C46ABB3B4 FOREIGN KEY (hebergement_type) REFERENCES hebergement_type (id) NOT DEFERRABLE INITIALLY IMMEDIATE);

用于hebergement_type的DDL

CREATE TABLE hebergement_type (id INTEGER NOT NULL, category VARCHAR(255) DEFAULT NULL, sub_category VARCHAR(255) DEFAULT NULL, label VARCHAR(128) DEFAULT NULL, PRIMARY KEY(id));

我添加hebergement_count只是说有5个immo,5个酒店,2个appart vacances,3个工作室等。

注意: 我需要让查询在doctrine2存储库中工作......

0 个答案:

没有答案