-1

我有一个“交易”表,其中包含“id”、“name”、“created_at”......列。我有一个“speciallisting_deal”数据透视表,它保持特殊列表和交易之间的关系。它的列是“id”、“deal_id”、“speciallisting_id”...。

就我而言,speciallisting_id 是肯定的,比如说 10。根据某些标准(如按 created_at 排序等)从“交易”表中获取结果时,我想优先考虑(我的意思是我想在顶部看到它们结果)到“交易”中的行,其 id 在此“(SELECT deal_id FROM speciallisting_deal WHERE speciallisting_id = 10)”或等效项中。

我怎样才能做到这一点?

4

2 回答 2

1

您可以使用以下case语句order by

order by (case when specialist_id = 10 then 0 else 1 end),
         created_at desc
于 2013-04-03T14:06:02.320 回答
0

一个简单的左连接可能就足够了。不过,最好提供您自己尝试做的事情。

SELECT

    d.id,
    d.name,
    d.created_at,
    -- Find out if this is considered "special"
    IF(sd.id IS NULL,0,1) AS isSpecial

FROM deals d

-- Left join the speciallistings onto this
LEFT JOIN speciallisting_deal sd
    ON sd.deal_id = d.id
    -- You don't have to specify a specific ID if you just want to get all that are special
    AND sd.speciallisting_id = 10
    -- You could do multiple speciallisting_id's using IN
    -- AND sd.speciallisting_id IN (8,2,10,314)

ORDER BY 
    isSpecial DESC, 
    d.created_at DESC
于 2013-04-03T14:09:59.750 回答