[英]how check id is in the group_concat field?
我有一個查詢,該查詢從某個表返回文件及其標簽和子類別,我想獲取帶有特殊標簽ID的文件。
SELECT file.id,file.title,content,comments,likes,visit,
group_concat(distinct sub_category_name ) as subCategoryName,
group_concat(distinct sub_category.id ) as subCatId,
GROUP_CONCAT(distinct tag_name order by tag_id) as tag_name,
GROUP_CONCAT(distinct tag_id order by tag_id) as tags_id
FROM file
LEFT JOIN file_subcat on file_subcat.file_id= file.id
LEFT JOIN sub_category on sub_category.id=file_subcat.subcat_id
LEFT JOIN tag_file tf1 on tf1.file_id=file.id
LEFT JOIN tag on tag_id=tag.id
group by file.id
HAVING tags_id LIKE ?
ORDER BY file.id DESC
如果我使用此查詢,並且如果tags_id等於6,則返回6,16,...如何更改此查詢以獲取具有該標簽ID的文件? 而且我不想從基礎更改查詢,因為我想顯示每個文件標簽和子類別,並且此查詢似乎很有效,因為我不需要多個查詢。 結果集是這樣的
file_id tags_id
1 6,15,16
2 7,20,26
3 8,9,10
如果我在表中使用了此方法,則可以在In()中使用它,但由於要獲得此結果,因此我使用了group by和hading,並且似乎無法在Haves子句中使用IN或BETWEEN。
喜歡這個問題,試試看,
SELECT file.id,file.title,content,comments,likes,visit,
group_concat(distinct sub_category_name ) as subCategoryName,
group_concat(distinct sub_category.id ) as subCatId,
GROUP_CONCAT(distinct tag_name order by tag_id) as tag_name,
GROUP_CONCAT(distinct tag_id order by tag_id) as tags_id
FROM file
LEFT JOIN file_subcat on file_subcat.file_id= file.id
LEFT JOIN sub_category on sub_category.id=file_subcat.subcat_id
LEFT JOIN tag_file tf1 on tf1.file_id=file.id
LEFT JOIN tag on tag_id=tag.id
group by file.id
HAVING FIND_IN_SET('16', tags_id)
ORDER BY file.id DESC
將<'16'>替換為所需的ID /值,我敢肯定您會獲取它,也可以通過以下方式排除GROUP_CONCAT中的特定值:
HAVING !FIND_IN_SET('16', tags_id)
忘記使用串聯的值。 為什么可以搜索字符串:
HAVING SUM(tag_id = ?) > 0
這將保存所有字符串操作。 另外,如果tag_id
是整數,則可以將其作為數字進行比較,而不用在類型之間來回轉換值。
通過閱讀您的SQL,就好像您正在使用LIKE運算符一樣。 使用LIKE運算符將搜索類似於或等於指定變量(LET?=變量)的內容,嘗試更改查詢以使用直接比較運算符,例如=(等於),類似;
SELECT file.id,file.title,content,comments,likes,visit,
group_concat(distinct sub_category_name ) as subCategoryName,
group_concat(distinct sub_category.id ) as subCatId,
GROUP_CONCAT(distinct tag_name order by tag_id) as tag_name,
GROUP_CONCAT(distinct tag_id order by tag_id) as tags_id
FROM file
LEFT JOIN file_subcat on file_subcat.file_id= file.id
LEFT JOIN sub_category on sub_category.id=file_subcat.subcat_id
LEFT JOIN tag_file tf1 on tf1.file_id=file.id
LEFT JOIN tag on tag_id=tag.id
WHERE tags_id = ?
group by file.id
ORDER BY file.id DESC
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.