带有访问ID的MySQL Query建议

时间:2013-11-22 10:14:24

标签: mysql

我有一个像这样的MySQL表

ownerlisting_access_id   property_id    mainaccess_id   subaccess_id access_value
 62                      2              35      41           Yes
 64                      2              35      36           Yes
123                      4              35      41       Yes
125                      4              35      36       Yes
306                      7              35      41       Yes
307                      7              35      42       Yes
308                      7              35      36       Yes

我想要一个查询,它会使用subaccess_id(41,42,36)和mainaccess_id(35) -

给我这个输出
ownerlisting_access_id   property_id    mainaccess_id   subaccess_id    access_value
 306                     7              35              41              Yes
 307                     7              35              42              Yes
 308                     7              35              36              Yes

我需要使用41,42,36

的子访问ID获取property_id为7

4 个答案:

答案 0 :(得分:1)

获得问题答案的最快方法是描述问题而不仅仅是显示您需要的结果。目前尚不清楚你想要的输出背后的逻辑是什么。我猜您需要每个组property_id具有最高subaccess_id的行。如果是这样,这里是查询:

select * from t 
join (select subaccess_id, max(property_id) MAX_property_id 
        from t 
        where mainaccess_id=35
              and 
              subaccess_id in (41,42,36) 
        group by subaccess_id
      ) t1
      on t.subaccess_id=t1.subaccess_id
         and 
         t.property_id=t1.MAX_property_id

SQLFiddle demo

此处还有一个输出您需要的结果的查询:)但我想这并不能解决您的问题:

select * from t where property_id=7

答案 1 :(得分:0)

试试这个:

SELECT table1.* FROM (
select property_id, group_concat(DISTINCT subaccess_id ORDER BY subaccess_id) as list
from table1 as t1 group by property_id
  ) a, table1
WHERE a.property_id = table1.property_id
AND a.list = '36,41,42'

工作查询:http://sqlfiddle.com/#!2/4744ea/2

答案 2 :(得分:-1)

SELECT MAX(DISTINCT property_ID) AS property_ID, mainaccess_id, 
MAX(DISTINCT subaccess_id) AS subaccess_id, MAX(DISTINCT access_value) 
FROM tableName GROUP BY mainaccess_id ORDER BY  mainaccess_id

答案 3 :(得分:-1)

SELECT property_ID, mainaccess_id, subaccess_id, access_value
FROM tableName t1
WHERE t1.mainaccess_id = 35 
AND (t1.subaccess_id = 41 OR t1.subaccess_id = 42 OR t1.subaccess_id = 36)
AND t1.property_ID = (SELECT MAX(t2.property_ID)
                    FROM tableName t2
                    WHERE t2.mainaccess_id = 35 
                    AND (t2.subaccess_id = 41 OR t2.subaccess_id = 42 OR t2.subaccess_id = 36))