0

これを適切に尋ねる方法がよくわかりません。これはおそらく私の問題の一部です。「優先度」と呼ばれる列によって区別された多くの同様のレコードを持つデータベースが存在します。同じ「タイプ」と「プロジェクト」IDを持つ優先度の高いレコードを取得したいと思います。たとえば、テーブルは次のようになります。

id  project_id type_id  priority 
1   66          14      0
2   66          14      10
3   66          16      0

現在、プログラムはプロジェクトを介して選択し、次のように入力します。

Select * FROM table WHERE project_id = 66;

そして、結果をループし、同じレコードが複数ある場合は、優先度の低いレコードを破棄しますtype_id。選択を介してこれを行う方法はありますか?

理想的な結果セットは次のようになります。

id  project_id type_id  priority 
2   66          14      10
3   66          16      0

優先度の低い type_id 14 レコードを破棄した場所。テーブル内に同じ type_id を持つ項目が 2 つ以上ある場合があります。

4

3 に答える 3

0
Select * FROM table GROUP BY project_id, type_id ORDER BY priority DESC
于 2013-08-07T19:40:31.003 に答える
0
SELECT *
FROM table
JOIN (
    SELECT project_id, type_id, MAX(priority) AS max_priority
    FROM table
    GROUP BY project_id, type_id
) AS maxima -- subquery returns one row per group (project_id, type_id) along with the highest priority in each group 
-- join this with the main table
ON maxima.project_id = table.project_id
AND maxima.type_id = table.type_id
AND maxima.max_priority = table.priority
于 2013-08-07T19:40:44.743 に答える
0

取得が難しい唯一のフィールドはid. そして、あなたはそれを得るためにgroup_concat()トリックを使うことができます.

select project_id, type_id, max(priority) as priority,
       substring_index(group_concat(id order by priority desc), ',', 1) as id
from t
group by project_id, type_id;

project_idこれにより、最大の ID を取得し、 /type_idの組み合わせごとにそのような行を 1 つだけ取得することが保証されます。

于 2013-08-07T19:56:52.813 に答える