我有一个“deal”表,其中包含“id”,“name”,“created_at”......列。 我有一个“speciallisting_deal”数据透视表,它保持特殊列表和交易之间的关系。它的列是“id”,“deal_id”,“speciallisting_id”......
在我的情况下,speciallisting_id是肯定的,比方说10.根据某些标准(如created_at等排序)从“deal”表中获取结果,我想优先考虑(我的意思是我想看到它们)在结果的顶部)到“交易”中的行,其中的ID是“(SELECT deal_id FROM speciallisting_deal WHERE speciallisting_id = 10)”或等价物。
我该怎么做?
答案 0 :(得分:1)
您可以在case
中使用order by
语句:
order by (case when specialist_id = 10 then 0 else 1 end),
created_at desc
答案 1 :(得分: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