0

MySQLデータベースには、アイテムを説明するいくつかの列を持つテーブルアイテムと、別のテーブルitemExtendedFieldsがあります。2番目の列には、id、itemId、name、valueの列があります。itemExtendedFieldsには、アイテムに関する追加情報が格納されます。

一部のアイテムには、 itemExtendedFieldsテーブルの2つの行に保持されている2つの値から構築できる有効期限があります。たとえば、itemId = 34の​​アイテムの場合、itemExtendedFieldsに次の2つの行があります。

id | itemId | name | value
--------------------------
87 | 34 | ExpiryYear | 2014
88 | 34 | ExpiryMonth | 2

itemExtendedFieldsテーブルのexpiryYear値とExpiryMonth値とともに、アイテムからすべてのアイテムを個別の列に選択するクエリを作成する必要があります。さらに、特定の日付(たとえば、2014年2月)に期限切れになるアイテムを選択する必要があります。適切なクエリを作成する方法がわかりません。テーブルの構成を変更することはできません。

4

3 に答える 3

2

これにより、テーブルとitemsテーブルのすべての列が一覧表示されます。ExpiryYearExpiryMonthitemExtendedFields

SELECT  a.*, b.ExpiryYear, b.ExpiryMonth
FROM    items a
        INNER JOIN 
        (
            SELECT  itemID,
                    MAX(CASE WHEN name = 'ExpiryYear' THEN `value` ELSE NULL END) ExpiryYear,
                    MAX(CASE WHEN name = 'ExpiryMonth' THEN `value` ELSE NULL END) ExpiryMonth 
            FROM    itemExtendedFields
            GROUP BY itemID
        ) b ON a.itemID = b.itemID
WHERE   b.ExpiryYear = 2012 AND 
        b.ExpiryMonth = 2
于 2013-01-03T14:50:28.733 に答える
1

It is not exactly clear what you are trying to do but since you have the values in a single column, it might be easier to pivot the data in the itemExtendedFields table first, then filter similar to this:

select *
from
(
    select i.id,
        MAX(case when f.name = 'ExpiryYear' then f.value end) ExpiryYear,
        MAX(case when f.name = 'ExpiryMonth' then f.value end) ExpiryMonth
    from item i
    left join itemExtendedFields f
        on i.id = f.itemid
    group by i.id
) src
where ExpiryYear = 2014
    and ExpiryMonth = 2

This pivoting is taking the values which are stored in a single column/multiple rows and places it into multiple columns with a single row. It might be possible to add more columns from the item table to the subquery or you can join this subquery back to the item table to get the additional details.

Similar to this:

select *
from item i
left join 
(
    select f.itemid,
        MAX(case when f.name = 'ExpiryYear' then f.value end) ExpiryYear,
        MAX(case when f.name = 'ExpiryMonth' then f.value end) ExpiryMonth
    from itemExtendedFields f
    group by f.itemid
) src
   on i.id = src.itemid
where src.ExpiryYear = 2014
    and src.ExpiryMonth = 2
于 2013-01-03T14:51:22.360 に答える
0
SELECT ItemId,
       MAX(CASE WHEN name = 'ExpiryYear' THEN value END) ExpiryYear,
       MAX(CASE WHEN name = 'ExpiryMonth' THEN value END) ExpiryMonth
FROM itemExtendedFields
GROUP BY itemId

SQLフィドル

于 2013-01-03T14:53:57.587 に答える