GROUP_CONCAT中的条件

时间:2019-04-15 07:52:39

标签: mysql sql

enter image description here

我正在尝试获取标签“ car”不存在的图像ID。 我尝试将与特定图像ID相关的所有对象标签分组。

我正在尝试排除其中包含“汽车”的图片ID。 但是,不是唯一的对象标签“ car”被排除在组中。

我已经尝试过-

SELECT used_car_image_id, GROUP_CONCAT(DISTINCT object_label ORDER BY object_label ASC SEPARATOR ',')
FROM individual_used_cars_image_label 
GROUP BY used_car_image_id
HAVING GROUP_CONCAT(DISTINCT object_label ORDER BY object_label ASC SEPARATOR ',') != 'car'

还有-

SELECT used_car_image_id, GROUP_CONCAT(DISTINCT object_label ORDER BY object_label ASC SEPARATOR ',')
FROM individual_used_cars_image_label 
WHERE object_label !='car'
GROUP BY used_car_image_id

两个查询都给出了ID,只是排除了对象标签“ car”。 输出应该是图像ID的行,其中没有名为“ car”的对象标签

3 个答案:

答案 0 :(得分:1)

您可以添加与每个let str = "junkasdojf :text:" //You can use `try!` when you are sure your pattern is valid. //And do not miss `+` after `[a-z]`. let regex = try! NSRegularExpression(pattern: ":[a-z]+:", options: .caseInsensitive) //Use `str.utf16.count`, not `str.count`. if let match = regex.firstMatch(in: str, range: NSRange(0..<str.utf16.count)) { //Use `Range.init(_:in:)` to convert `NSRange` to `Range<String.Index>`. let range = Range(match.range, in: str)! //When you can accept `Substring`, `String.init(_:)` is not needed. let matchingStr = String(str[range]) print(matchingStr) //->:text: } else { print("*NO mathes*") } 关联的object_label个值中的多少等于used_car_image_id的计数,然后使用该计数来过滤结果。此查询利用了MySQL在数字上下文中将布尔表达式视为1(true)或0(false)的事实。

car

Demo on dbfiddle

答案 1 :(得分:0)

您应该在CASE子句中使用HAVING表达式,该表达式检查car的存在:

SELECT used_car_image_id, GROUP_CONCAT(DISTINCT object_label ORDER BY object_label SEPARATOR ',') labels
FROM individual_used_cars_image_label 
GROUP BY used_car_image_id
HAVING COUNT(CASE WHEN object_label = 'car' THEN 1 END) = 0;

答案 2 :(得分:0)

您可以使用不存在的标签轻松排除带有标签“ car”的图像ID:

SELECT 
  t.used_car_image_id, 
  GROUP_CONCAT(DISTINCT t.object_label ORDER BY t.object_label ASC SEPARATOR ',') labels
FROM individual_used_cars_image_label t 
WHERE NOT EXISTS (
  SELECT 1 FROM individual_used_cars_image_label
  WHERE used_car_image_id = t.used_car_image_id AND object_label ='car' 
)
GROUP BY t.used_car_image_id