内部联接与子查询以从数据透视表中筛选记录

[英]Inner join with sub query to filter record from pivot table


This is my query

这是我的疑问

 SELECT t.*
 FROM `User` `t`
 INNER JOIN (
     SELECT cv.relatedId
     FROM CustomValue cv
     WHERE (cv.customFieldId=11 AND (cv.fieldValue like '%dsasda%')) OR (cv.customFieldId=15 AND (cv.fieldValue like '%1%'))
     GROUP BY cv.relatedId
     HAVING count(*) >= 1
) tblcv  ON  tblcv.relatedId = t.id

I need to do add a AND CONDITION. i am wondering how to.

我需要添加一个AND CONDITION。我想知道如何。

This is the data set.

这是数据集。

enter image description here

As circled in blue, I need to compare against both records for a particular relatedId.

如蓝色圆圈所示,我需要比较特定relatedId的两个记录。

For example, for related id 4031 I need to check if customFieldId = 11 and fieldValue like %dsasda% and if customFieldId = 15 and fieldValue like '%1%'

例如,对于相关的id 4031,我需要检查customFieldId = 11和fieldValue是否为%dsasda%,如果customFieldId = 15,fieldValue是否为'%1%'

So the result of query for this data set should have 4031 relatedId as an answer but I get all 3 related id result. it seems to be using OR CONDITION.

因此查询此数据集的结果应该有4031 relatedId作为答案,但我得到所有3个相关的id结果。它好像在使用OR CONDITION。

enter image description here

When try to use AND condition. i dont get any results. This is with AND condition.

当尝试使用AND条件时。我没有得到任何结果。这是AND条件。

SELECT cv.relatedId
FROM CustomValue cv
WHERE (cv.customFieldId=11 AND (cv.fieldValue like '%dsasda%')) AND (cv.customFieldId=15 AND (cv.fieldValue like '%1%'))
GROUP BY cv.relatedId
HAVING count(*) >= 1

1 个解决方案

#1


1  

If you want to match both conditions then you need to match at least 2 rows in your having

如果您想要匹配这两个条件,那么您需要匹配至少2行

HAVING count(*) >= 1
                 ^ remove equality operator

You're getting back the 2 other id's because they each match 1 row (you've circled them).

你得到了另外两个id,因为它们各自匹配1行(你已经圈出了它们)。

If (relatedId,fieldValue) is not unique, then use distinct to make sure each group has both values.

如果(relatedId,fieldValue)不唯一,则使用distinct来确保每个组都具有这两个值。

HAVING count(distinct fieldValue) > 1
智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2015/11/13/7200948d422d6bdf1a486c29bc8909d1.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告