SOQL join in salesforce - soql

How i can access attachment id from this query..
List<Email__c> e=[SELECT email_body__c,(SELECT Id,Name FROM Attachments) FROM Email__C where id='emailobjectid'];
for(email__c e1:e)
{
System.debug(e1.Attachments.id);
}
Getting error.. Invalid foreign key relationship Email__c.Attachments

Split the query.
List<Email__c> e=[SELECT id, email_body__c FROM Email__C where id='emailobjectid'];
for(email__c e1:e){
List<Attachments> attList = [SELECT Id,Name FROM Attachments where parentId=:e1.id];
for(Attachment att:attList)
System.debug(att.id+' '+att.name);
}

Related

SOQL Query with a Subquery that uses GROUP BY and HAVING throws unknown error

I'm trying to query a list of records from a custom object (SB_User__c) where the value in the Email__c field is not unique.
The following query captures the entire table as expected:
SELECT Id, Name, Email__c, External_Id__c
FROM SB_User__c
ORDER BY Email__c, Name
And my subquery returns a list of Email__c values that are not unique:
SELECT Email__c
FROM SB_User__c
GROUP BY Email__c
HAVING COUNT(Id) > 1
But when these queries are combined, I receive an unknown error:
SELECT Id, Name, Email__c, External_Id__c
FROM SB_User__c
WHERE Email__c IN (
SELECT Email__c FROM SB_User__c
GROUP BY Email__c
HAVING COUNT(Id) > 1)
ORDER BY Email__c, Name
Is there a way to accomplish what I'm trying to without involving apex?
i think the problem is probably in the having clause, i already run a similar query with this editor online:
online editor for sql queries
SELECT * FROM Customers
WHERE CustomerID IN (
SELECT CustomerID FROM Customers
GROUP BY CustomerID
HAVING CustomerID > 50)
ORDER BY Country ASC, CustomerName DESC;
and this query runs just ok, you can check the having clause.

DELETE from a Join in SQLite / syntax for IN clause on tuples?

I have a schema which uses a compound primary key to store users and associated data, like so:
CREATE TABLE users (
domain integer,
userid integer,
...
PRIMARY KEY (domain, userid)
);
CREATE TABLE userdata (
domain integer,
userid integer,
key integer,
...
PRIMARY KEY (domain, userid, key),
FOREIGN KEY (domain, userid) REFERENCES users(domain, userid)
);
I cannot make changes to this schema, nor can I opt to use another DBMS.
I want to delete some rows in userdata, based on a criterion over users. Conceptually, i'd like to do something like:
DELETE FROM userdata
WHERE (domain, userid) IN (
SELECT domain, userid FROM users WHERE <some condition>
) AND key = some_constant;
Or alternatively
DELETE ud FROM userdata ud
INNER JOIN users u on u.domain = ud.domain and u.userid = ud.userid
WHERE <some condition over u>
AND ud.key = some_constant
But sqlite3 (3.8.2) rejects both forms, the former with
Error: near ",": syntax error
and the latter with
Error: near "ud": syntax error
Annoyingly, the IN syntax works perfectly well when the join key consists of a single column.
What is the proper syntax or technique for achieving this ?
Not a SQLite user but I'd try selecting the ROWIDs to delete in userdata. I mean something like
delete from userdata
where rowid in (
select ud.rowid
from userdata ud
join users u on ...
where condition
)
I am supposing you want to delete key from user_data and x,y,z condition on user.
DELETE ud.key FROM user_data AS ud
LEFT JOIN users AS u ON ud.user_id = u.user_id
WHERE u.something='condition'
Your first attempt does not work because tuples (or whatever they are called) are not supported by SQLite (supported syntax here).
Your second attempt is invalid syntax as there is no JOIN in DELETE statements (maybe as an extension introduced by some DBMS but not in SQL92 apparently).
What you can try instead is:
DELETE FROM userdata
WHERE domain IN (SELECT u.domain FROM users u WHERE <some condition>)
AND userid IN (SELECT u.userid FROM users u WHERE <some condition> AND domain = u.domain)
AND key = some_constant;

How I can insert multiple records in one SQLite query?

I need insert multiple records in my DB SQLite.
I get an ArrayList with objects type "Nota", and I need insert this ArrayList completely.
My Object "Nota" has method getId and getTitle. So I can do arrayList_nota.get(Attribute) to get all attributes and insert.
My DB SQLite has: | ID | Title | Date | Text |
But I do not know if it is possible. And I do not know this query sintax. I need insert every position of array and her attributes.
How I can insert multiple records in one SQLite query?
Insert into Nota (ID,Title,Date,Text)
Select '1','LOTR 1','2010-01-01','Lord of The Rings 1'
union Select '2','LOTR 2','2010-02-01','Lord of The Rings 2'
union Select '3','Lotr 3','2010-03-01', 'Lord of the Rings 3';`
This is not a one sql statement solution.
try {
// db is your SQLiteDatabase object.
db.beginTransaction();
for ( Nota n : arrayList_nota ) {
ContentValues values = new ContentValues();
values.put( ID, n.getId() );
values.put( TITLE, n.getTitle() );
values.put( DATE, n.getDate() );
values.put( TEXT, n.getText() );
db.insert( TABLE_NAME, null, values );
}
db.setTransactionSuccessful();
} catch ( SQLiteException e ) {
// handle your sqlite database exceptions.
} finally {
db.endTransaction();
}

Giving alias in JOIN command in sqldatasource

I am using JOIN command to connect two tables in SqlDataSource.
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:CS %>"
SelectCommand="SELECT UserName as UN, AboutMe, WebPage, Email FROM Users JOIN ProfileImages ON ProfileImages.UserName = Users.UN WHERE (UN = #UserName)" >
</asp:SqlDataSource>
In MS SQL Server Management Studio this command is ok. But in the SqlDataSource it return errors - Invalid column name 'UN', Ambiguous column name 'UserName'
How do I alias this command right in SqlDataSource to not return these errors?
Your query is a bit wrong
You used alias i a wrong way
First:
You can use alias in the following sections:
Fields. Example Username as UN
Tables names: UserTable as US
In the order by section example: Order BY UN Desc
This because the sql runs the query operations in the following sequence:
FROM clause
WHERE clause
GROUP BY clause
HAVING clause
SELECT clause
ORDER BY clause
So because the FROM clause runs first the sql doesn't know about the alias in the SELECT clause
Take a look on a correct query
SELECT
UserName as UN,
AboutMe,
WebPage,
Email
FROM Users
JOIN ProfileImages ON ProfileImages.UserName = Users.UserName
WHERE (Users.UserName = #UserName)
I'm not an expert at SQL, but if both ProfileImages and Users contain the column 'UserName', then in your select columns you need to specify the table from which the UserName is pulled. So something like:
SELECT Users.UserName as UN, Users.AboutMe, Users.WebPage, Users.Email
FROM Users
JOIN ProfileImages ON ProfileImages.UserName = Users.UserName
WHERE (Users.UserName = #UserName)
You cannot use the column alias in the where clause.
SELECT UserName as UN, AboutMe, WebPage, Email
FROM Users usersAlias JOIN ProfileImages piAlias ON piAlias.UserName = usersAlias.UserName
WHERE (usersAlias.UserName = #UserName)
It makes sense when you look at the order of execution:
http://blog.sqlauthority.com/2009/04/06/sql-server-logical-query-processing-phases-order-of-statement-execution/
Since the order of execution is:
These phases and their orders are given as follows:
FROM
ON
OUTER
WHERE
GROUP BY
CUBE | ROLLUP
HAVING
SELECT
DISTINCT
10 ORDER BY
TOP
When these are being processed (the "from" (#1) and "on" (#2) and "where" (#4))..they have no knowledge about the "select" (#8) (aka, the alias name for UN), the column alias in the select clause cannot be used in the WHERE and FROM (and ON) clauses.

display columns from different tables during data bind

How to bind data from two tables.
tbl_user
first name userid
tbl_usermessage
userid timereceived msgid
How to display username and timereceived in datagrid
SELECT TimeReceived, FirstName FROM tbl_usermessage INNER JOIN tbl_user on tbl_usermessage.tbl_user_UserID = tbl_user.UserID WHERE tbl_message_MsgID = #Value1";
This is what I am trying i am getting syntax error. here Time received is from tbl_usermessage and firstname is from tbl_User and both table has userid
How about joining both tables on your sql query?
You need to connect a SqlDataSource to your DataGrid by setting the SqlDataSource's DataSourceID property to the SqlDataSourceID. Set the SqlDataSource's SelectCommand property to the SQL required to get the items:
SelectCommand="SELECT tableone.username, tableone.userid, tabletwo.userid, tabletwo.timereceived
FROM tableone INNER JOIN tabletwo ON tableone.userid=tabletwo.userid"
And also set the ConnectionString property:
ConnectionString="<%$ ConnectionStrings:MyDatabaseConnectionString %>" >
You need to retrieve the data from your database with a SQL Query which JOINs the two tables on a column that is common to both:
Something along these lines:
SELECT
userId, username, timereceived
FROM
Table1 INNER JOIN Table2 ON Table1.userId = Table2.UserID
Here's an example for your reference.

Resources