Two queries return different data - sql

I am running two queries according to me both should return same result, but i think i am missing something
SELECT "id", "email", "first_name", "last_name", locale
FROM "users" AS "users"
WHERE (
EXISTS (
SELECT cf.field_value, ucf.field_value
FROM custom_fields cf
LEFT JOIN users_custom_fields ucf ON cf."id" = ucf.custom_field_id
WHERE cf."id" = 272 AND
((
cf.field_value = 'true') OR
(
ucf.user_id = users.id AND ucf.field_value = 'true'))
))
it returns record
SELECT users.id, cf.field_value, ucf.field_value, ucf.user_id
FROM users
Join custom_fields cf on cf.user_id = users.id
LEFT join users_custom_fields ucf on ucf.custom_field_id = cf."id"
WHERE cf."id" = 272 AND
((
cf.field_value = 'true') OR
(ucf.user_id = users.id AND ucf.field_value = 'true'))
and it doesn't return anything, is there any difference between these two?

your second query you also join custom_fields table with cf.user_id = users.id. first query does not have this.
With adding cf.user_id = users.id, your first query equal the second.
SELECT "id", "email", "first_name", "last_name", locale FROM "users" AS "users" WHERE (
EXISTS (
SELECT cf.field_value, ucf.field_value
FROM custom_fields cf
LEFT JOIN users_custom_fields ucf ON cf."id" = ucf.custom_field_id
WHERE cf."id" = 272
AND cf.user_id = users.id
AND (( cf.field_value = 'true') OR
( ucf.user_id = users.id AND ucf.field_value = 'true'))
))

Related

How to do a SQL JOIN where multiple joined rows need to contain things

When someone on my site search for an image that has multiple tags I need to query and find all images that have the searched tags, but can't seem to figure out this query.
I have an Images table.
The Images table has a relation to Posts_Images.
Posts_Images would have a relation to Posts table.
Posts has a relation to Posts_Tags table.
Posts_Tags table will have the relations to Tags table.
The query I have so far:
SELECT "images".* FROM "images"
INNER JOIN "posts_images" ON posts_images.image_id = images.id
INNER JOIN "posts" ON posts.id = posts_images.post_id AND posts.state IS NULL
INNER JOIN "posts_tags" ON posts_tags.post_id = posts.id
INNER JOIN "tags" ON posts_tags.tag_id = tags.id
WHERE (("images"."order"=0) AND ("images"."has_processed"=TRUE)) AND (LOWER(tags.tag)='comic') AND ("tags"."tag" ILIKE '%Fallout%') ORDER BY "date_uploaded" DESC LIMIT 30
It gets no results, it is checking if the tags equals both values, but I want to see if any of the tags that were joined have all the values I need.
The desired result would be any Post that has a tag matching Comic and ILIKE '%Fallout%'
You seem to want something like this:
SELECT i.*
FROM images JOIN
posts_images pi
ON pi.image_id = i.id JOIN
posts p
ON p.id = pi.post_id AND p.state IS NULL JOIN
posts_tags pt
ON pt.post_id = p.id JOIN
tags t
ON pt.tag_id = t.id
WHERE i."order" = 0 AND
i.has_processed AND
(LOWER(t.tag) = 'comic') OR
(t.tag ILIKE '%Fallout%')
GROUP BY i.id
HAVING COUNT(DISTINCT tag) >= 2
ORDER BY date_uploaded DESC
LIMIT 30;
The logic is in the HAVING clause. I'm not 100% sure that this is exactly what you want for multiple matches.
In addition to gordon-linoff’s response - query can be described using ActiveQuery:
Images::find()
->alias('i')
->joinWith([
'postsImages pi',
'postsImages.posts p',
'postsImages.posts.tags t'
])
->where([
'p.state' => null,
'i.order' => 0,
'i.has_processed' => true,
])
->andWhere(
'or'
'LOWER(t.tag) = "comic"',
['like', 't.tag', 'Fallout']
])
->groupBy('id')
->having('COUNT(DISTINCT tag) >= 2')
->orderBy('date_uploaded DESC')
->limit(30)
->all()
$images = Images::find()
->innerJoin('posts_images', 'posts_images.image_id = images.id')
->innerJoin('posts', 'posts.id = posts_images.post_id AND posts.state IS NULL')
->where(['images.order' => 0, 'images.has_processed' => true]);
if (!is_null($query)) {
$tags = explode(',', $query);
$images = $images
->innerJoin('posts_tags', 'posts_tags.post_id = posts.id')
->innerJoin('tags', 'posts_tags.tag_id = tags.id');
$tagsQuery = ['OR'];
foreach ($tags as $tag) {
$tag = trim(htmlentities($tag));
if (strtolower($tag) == 'comic') {
$tagsQuery[] = ['tags.tag' => $tag];
} else {
$tagsQuery[] = [
'ILIKE',
'tags.tag', $tag
];
}
}
if (!empty($tagsQuery)) {
$images = $images->andWhere($tagsQuery)
->having('COUNT(DISTINCT tags.tag) >= ' . sizeof($tags));
}
}
$images = $images
->groupBy('images.id')
->orderBy(['date_uploaded' => SORT_DESC])
->offset($offset)
->limit($count);
return $images->all();

EclipseLink/TopLink full outer join instead left join

On model Card can have or not CardHolder ( 1:1 ), and I would like getting every cards filter by issuer linked to actived cardHolders plus cards without cardHolders, so I need a full outer join. Although the query below translate to left join returning just cards with cardHolders
final ExpressionBuilder builder = new ExpressionBuilder( Card.class );
Expression queryExp = builder.get( "cardIssuer" ).equal( cardIssuer );
queryExp = queryExp.and( builder.get( "cardStatus" ).get( "statusType" ).equal( "ACTIVATED" ) );
queryExp = queryExp.and( builder.getAllowingNull( "cardHolder" )isNull().or(
builder.get( "cardHolder" ).get( "status" ).get( "status" ).equal( "ACTIVE" ) ) );
Expression orderExpression = builder.get( "cardHolder" ).get( "surname" ).descending();
return getMultiple( queryExp, pageable , Card.class, orderExpression );
Translate query is
SELECT COUNT(t0.CARD_ID) FROM CARD t0 LEFT JOIN CARD_HOLDER t3
ON (t3.CARD_HOLDER_ID = t0.CARD_HOLDER_ID), CARD_HOLDER_STATUS t2, CARD_STATUS t1
WHERE (((((t0.CARD_ISSUER_ID = 10006) AND (t1.STATUS_TYPE = 'ACTIVATED')) AND (t2.STATUS = 'ACTIVE'))
AND (t0.CARD_ID IN ('52683','52692')))
AND ((t1.CARD_STATUS_ID = t0.CARD_STATUS_ID) AND (t2.STATUS_ID = t3.STATUS_ID)))
Due to JPA version the outer join is not properly done, so I found a way through native queries
#NamedNativeQueries( {
#NamedNativeQuery( name = Card.USER_DIRECTORY_BASE,
query = "select * from card c full outer join card_holder ch on c.card_holder_id = ch.card_holder_id "
+ "where c.CARD_ISSUER_ID = ?1 and c.card_status_id = 1 and ( ch.STATUS_ID = 1 or c.CARD_HOLDER_ID is null) "
+ "order by ch.FORENAME asc",
resultClass = Card.class ),
#NamedNativeQuery( name = Card.USER_DIRECTORY_BASE_COUNT,
query = "select count(*) from card c full outer join card_holder ch on c.card_holder_id = ch.card_holder_id "
+ "where c.CARD_ISSUER_ID = ?1 and c.card_status_id = 1 and ( ch.STATUS_ID = 1 or c.CARD_HOLDER_ID is null) "
+ "order by ch.FORENAME asc" )
} )
And getting results
Query query = em.createNamedQuery( Card.USER_DIRECTORY_BASE);
query.setParamenter(1,10000);
query.getResultList();

Convert SQL query with inner, left, and nested select to LINQ

how can convert this query to linq?
SELECT p.PostID, p.PostText, p.PublishDate, u.Name
FROM AspNetUsers u INNER JOIN Posts p ON u.Id = p.PostUserID LEFT JOIN Reposts r ON p.PostID = r.PostID
WHERE p.PostUserID = 'id'
OR p.PostUserID IN ( SELECT FollowingUserID FROM Friends WHERE FollowerUserID = 'id' AND isUnfollow = 0)
OR p.PostID in (SELECT PostID FROM Reposts WHERE RepostUserID = 'id' OR RepostUserID IN ( SELECT FollowingUserID FROM Friends WHERE FollowerUserID = 'id' AND isUnfollow = 0))
ORDER BY p.PostUserID
Does this work?
var results = from u in AspNetUsers
join p in Posts on u.Id equals p.PostUserID
join r in Reposts on p.PostId equals r.PostId into records
from record in records.DefaultIfEmpty()
where p.PostUserID == "id"
|| (from friend in Friends
where friend.FollowerUserID == "id"
&& friend.isUnfollow == 0
select friend.FollowingUserID
).Contains(p.PostUserID)
|| (from r2 in Reposts
where r2.RepostUserID == "id"
|| (from friend2 in Friends
where friend2.FollowerUserID == "id"
&& friend2.isUnfollow == 0
select friend2.FollowingUserID
).Contains(r2.RepostUserID)
select r2.PostID
).Contains(p.PostID)
orderby p.PostUserID ascending
select p.PostID, p.PostText, p.PublishDate, u.Name;

Zend select object - building a query

How can I write the query below in Zend Select object notation so using ->join()->where() etc?
SELECT t.id, t.user_id, t.added_date, u.id, u.phone, bk.call_status
FROM `transaction` t
INNER JOIN
(
SELECT id, MAX(added_date) AS addedDate
FROM `transaction`
GROUP BY id
) gt
ON t.id = gt.id AND t.added_date = gt.addedDate
LEFT JOIN `user` u ON t.user_id = u.id
LEFT JOIN `bok_call` bk ON bk.user_id = t.user_id
WHERE NOT t.user_id = 'null'
AND addedDate BETWEEN '2008-05-04 17:51:48' AND '2009-05-04 17:51:48'
AND NOT u.phone = ''
AND bk.call_status IS null
For example this way:
$joinSelect = $model->select()
->from('transaction'), array('id', 'addedDate' => 'MAX(added_date)'))
->group('id');
$select = $model->select()
->setIntegrityCheck(false)
->from(array('t' => 'transaction'), array('id', 'user_id', 'added_date'))
->join(array('gt' => $joinSelect), 't.id = gr.id AND t.added_date = gt.addedDate', array());
->joinLeft(array('u' => 'user'), 't.user_id = u.id', array('id', 'phone'))
->joinLeft(array('bk' => 'bok_call'), 'bk.user_id = t.user_id', array('call_status'))
->where('t.user_id != ?', 'null')
->where("addedDate BETWEEN '2008-05-04 17:51:48' AND '2009-05-04 17:51:48')
->where('u.phone != ?', '')
->where('bk.call_status IS NULL');
Be aware that you won't be able to differentiate 't.id' and 'u.id' in result.

Converting SQL to LINQ to Entity

I am trying to convert the following SQL, not written by myself, into a Linq to Entity query.
select
u.user_Id,
u.forename,
u.surname,
u.client_code,
u.user_name,
u.password,
u.email,
u.gender,
u.Report_Date,
u.EmailDate,
count(ut.test_Id) as testcount,
sum(cast(isnull(ut.completed,0) as int)) as Testcompleted,
u.job_function,
lu.lookupvalue
from
users u inner join user_Relationship ur
on u.user_Id= ur.child_Id
left join user_tests ut
on ut.user_id=u.user_id
inner join lookup lu on u.first_languageId = lu.lookupid
where ur.parent_Id = #Parent_Id
group by
u.user_Id, u.forename,u.surname,u.client_code,u.user_name, u.password,
u.email, u.gender, u.first_languageId, u.Report_Date,u.EmailDate,
u.job_function, lu.lookupvalue
So far, I have been able to do this:
from u in db.Users
join ur in db.User_Relationship on u.User_ID equals ur.Child_ID
join ut in db.User_Tests on u.User_ID equals ut.User_ID into ps
from ut in ps.DefaultIfEmpty()
join lu in db.Lookups on u.First_LanguageID equals lu.LookupID
where ur.Parent_ID == 45875
select new UserViewModel
{
User_ID = u.User_ID,
Forename = u.Forename,
Surname = u.Surname,
Client_Code = u.Client_Code,
User_Name = u.User_Name,
Password = u.Password,
Email = u.Email,
Gender = u.Gender,
Report_Date = u.Report_date,
Email_Date = u.EmailDate,
//Insert Test_Count and Test_Completed
Job_Function = u.Job_Function,
Lookup_Value = lu.LookupValue
});
How do I replicate the Group and Count() function of SQL?
Well tweak around this solution coz currently i dont have .Net environment for testing this solution, but you'll sure get how grouping is done in linq.
from u in db.Users
join ur in db.User_Relationship on u.User_ID equals ur.Child_ID
join ut in db.User_Tests on u.User_ID equals ut.User_ID into ps
from ut in ps.DefaultIfEmpty()
join lu in db.Lookups on u.First_LanguageID equals lu.LookupID
where ur.Parent_ID == 45875 group new{u,lu} by new {u.User_ID,u.Forename,
u.Surname,u.Client_Code,
u.User_Name,u.Password,
u.Email,u.Gender,u.Report_date,
u.EmailDate,u.Job_Function,
lu.LookupValue} into g
let Test_Count = ps.Count(x=>x.test_Id)
let Test_Completed = ps.Sum(x=>x.completed)
select new UserViewModel
{
User_ID = g.Key.User_ID,
Forename = g.Key.Forename,
Surname = g.Key.Surname,
Client_Code = g.Key.Client_Code,
User_Name = g.Key.User_Name,
Password = g.Key.Password,
Email = g.Key.Email,
Gender = g.Key.Gender,
Report_Date = g.Key.Report_date,
Email_Date = g.Key.EmailDate,
Test_Count = Test_Count,
Test_Completed = Test_Completed,
Job_Function = u.Job_Function,
Lookup_Value = lu.LookupValue
});