2017-03-26 31 views
0

我有這樣的SQL:MariaDB的 - 爲了與更多的選擇

select * from `posts` 
where `posts`.`deleted_at` is null 
and `expire_at` >= '2017-03-26 21:23:42.000000' 
and (
select count(distinct tags.id) from `tags` 
inner join `post_tag` on `tags`.`id` = `post_tag`.`tag_id` 
where `post_tag`.`post_id` = `posts`.`id` 
and (`tags`.`tag` like 'PHP' or `tags`.`tag` like 'pop' or `tags`.`tag` like 'UI') 
) >= 1 

是否有可能爲了顯示結果的帖子標籤號碼是多少? 也許添加別名?

任何信息都可以幫到我。

回答

1

將您的相關子查詢轉換爲連接:

select p.* 
from posts p 
join (
    select pt.post_id, 
     count(distinct t.id) as tag_count 
    from tags t 
    inner join post_tag pt on t.id = pt.tag_id 
    where t.tag in ('PHP', 'pop', 'UI') 
    group by pt.post_id 
    ) pt on p.id = pt.post_id 
where p.deleted_at is null 
    and p.expire_at >= '2017-03-26 21:23:42.000000' 
order by pt.tag_count desc; 

另外請注意,我改變了likeor的一羣單IN,因爲你不符合任何圖案即有字符串中沒有%。所以,最好使用單個IN來代替。另外,如果你已經定義了你的表名,列名等等,記住關鍵字等,你不應該有需要使用反引號。他們使閱讀查詢變得困難。

+0

我喜歡因爲Laravel。代碼是:$ this-> posts($ request) - > whereHas('tags',function($ q)use($ tags))其中(function($ q)use($ tags) {$ tags as $ tag} { }) - > select(DB :: raw($ tags = $ tag){ }) - > select(DB :: raw ('count(distinct tags.id)')); }) - > paginate(perPage());' – Maximi

+0

@Maximi - 對不起?我不明白你的意思。 – GurV

+0

Laravel擁有整個SQL的查詢生成器。我認爲你的SQL不能由Laravel構建。但答案當然很好。但現在沒有真正的解決方案。 – Maximi