I have a table which has one column's name and guestof .
I want to return a cursor to get three values : name guestOf and guestcount where guestcount is how many rows has "name" as the value of guestOf.
How can combine this internal query and return the result. Trying something like this, can it be done without inner query for better performance
SELECT name, guestCount from Table
as A outer join (SELECT guestOf , count(*)
AS GuestCount FROM Table group by guestOf)
as GuestCounts WHERE A.id = GuestCounts.guestOf
Give this code a go. I think it matches what you're looking for:
SELECT g.name, g.guestof,
(SELECT COUNT(guestof)
FROM guests AS c
WHERE g.name == c.guestof
) as guestcount
FROM guests AS g;
And as an example: SQLFiddle
Related
Let's say that I have two tables:
lessons with columns: lessonID, name
studentlessons with columns: lessonID, age
I am trying to perform this action:
SELECT lessons.*, studentlessons.* FROM studentlessons
JOIN lessons WHERE studentlessons.lessonID = lessons.lessonID
but the result is a table which have the columns:
lessonID, name, lessonID(1), age
I want to avoid the lessonID(1), so my desired output must be:
lessonID, name, age
I know that I can use this syntax:
SELECT lessons.lessonID, lessons.name, studentlessons.age FROM studentlessons
JOIN lessons WHERE studentlessons.lessonID = lessons.lessonID
but I can't because of some other reasons.
Is there any purely SQLite syntax that can give me my desired output?
What you want is a NATURAL JOIN:
SELECT * FROM studentlessons NATURAL JOIN lessons
which returns only one of the columns lessonID.
The tables are joined implicitly on the columns that have the same name(s).
See the demo.
I had following Table
CREATE TABLE Customer
( `Name` varchar(7), `Address` varchar(55), `City` varchar(15),`Contact` int,`timestamp` int)
;
INSERT INTO Customer
(`Name`,`Address`, `City`, `Contact`,`timestamp`)
VALUES
('Jack','New City','LA',79878458,456125),
('Joseph','New Lane23','LA',87458458,794865),
('Rosy','Old City','Paris',79878458,215125),
('Maria','New City','LA',79878458,699125),
('Jack','New City','LA',79878458,456125),
('Rosy','Old City','Paris',79878458,845125),
('Jack','New Main Street','New York',79878458,555525),
('Joseph','Near Bank','SAn Francisco',79878458,984521)
;
I want to get all customer record with highest timestamp without duplication.
Try the following.
select name,max(timestamp),Address,City,Contact from Customer group by name
I want to get all customer record with highest timestamp without
duplication.
Use DISTINCT operator and ORDER BY clause like
select distinct `Name`,`Address`, `City`, `Contact`,`timestamp`
from customer
order by `timestamp` desc;
In that case you can use JOIN query like
select t1.*
from customer t1 join
(select Name, max(`timestamp`) as maxstamp
from customer
group by Name) xx
on t1.Name = xx.Name
and t1.`timestamp` = xx.maxstamp;
Try this:
SELECT * FROM `customer`
group by name,Address,City,Contact,timestamp
order by timestamp desc
I'm joining the Customer table with itself, the condition c1.timestamp<c2.timestamp on the join clause combined with c2.timestamp IS NULL
will make sure that only the latest record for each person is returned. I put DISTINCT because on your sample data there are two records for Jack with the same timestamp:
SELECT DISTINCT
c1.*
FROM
Customer c1 LEFT JOIN Customer c2
ON c1.Name=c2.Name
AND c1.Contact=c2.Contact -- you might want to remove this
AND c1.timestamp<c2.timestamp
WHERE
c2.timestamp IS NULL
ORDER BY
Name, Address
Please see a fiddle here.
I'm super-novice at Android programming and have this project I'm stuck on.
I have a database of (conlang) dictionaries where each language is in its own table. The user searches these and the results will display in a ListView. Right now, I've got it working to search only one table.
I want it to be able to search all three tables and display the results in one ListView with rows from each of the tables. I'd like to indicate which table each row came from. The results would display something like:
From language
Lang Term : English term
Additional information
I've set up a CursorAdapter and have this currently working for one of the three tables.
...
Since the dictionaries came from different sources, they have different information. As an example:
One has the columns EngTerm, VLangTerm, FullDefinition
Another has EngTerm, RLangTerm, PartOfSpeech
And the other has EngTerm, GLangTerm, PartOfSpeech, and PronounciationGuide (possibly).
For example, table1 might contain results for "land," "landing gear" and "landscape" and table2 might contain "land," "landing" and "island" and table3 might contain "bland" and "homeland."
The user can search these tables right now only by the english term, and can select to match by full word or partial word.
Because of how they are structured, I'm guessing there is no way to do a JOIN query.
I don't know if this helps at all, but right now, I've got this method in my SQLiteOpenHelper class:
public Cursor searchDictionaryByEnglish
(boolean matchFullWordOnly, String searchTerm) {
String sql = "SELECT * FROM " + TABLE_VULCAN +
" WHERE " + COLUMN_ALL_ENG_TERM + " MATCH ?";
if (!matchFullWordOnly)
searchTerm = "*" + searchTerm + "*";
return mDataBase.rawQuery(sql, new String[]{searchTerm});
}
(It is an FTS3 table it's searching, thus the MATCH rather than LIKE.)
I hope I've made it clear what I'm trying to accomplish, but I'm not sure where to start. I've found some answers about MergeCursor but I don't know how to apply that because of the different number and names of columns.
Here's how to do a union if you don't have one of the columns in one of the tables, it will work if you're only searching through the common column, that all the tables have.
SELECT field1 ,
field2 ,
field3
FROM ( SELECT field1 ,
field2 ,
field3
FROM table1
UNION
SELECT field1 ,
field2 ,
field3
FROM table2
UNION
SELECT field1 ,
field2 ,
NULL AS field3
FROM table3
) tbl
WHERE tbl.field1 LIKE '%search_string%'
Note the NULL AS field3 in the last UNION.
Create a Adapter that does accept the fields you require to display.
I have two identical tables (month1, month2) and I am trying to find all records from both tables where task1_done = 1. I want the last row in that set (i move cursor to last for this). I have played with inner outer natural joins but can't seem to get month2 values. Here is what I have:
String query = "SELECT m1.columnA, m1.columnB, m1.columnC, m1.columnD, m1.columnE, m1.columnF FROM month1 m1, month2 m2 WHERE m1.task1_done = 1 OR m2.task1_done = 1";
Any help would be great!
I think you want a union all for this query:
select m.*
from (select *
from months1
union all
select *
from months2
) m
where task1_done = 1;
Note: I have used * as a convenience because you said the two tables have the same structure. You should actually list the columns that you want from the two tables.
In general, having two tables with the same layout is a sign of a bad database design. It is usually better to have a bigger table, with another column identifying "month1" or "month2".
EDIT:
SQL tables do not have a "last" value. If you have a an id or timestamp column that you can use for ordering, then you can do:
select m.*
from (select *
from months1
union all
select *
from months2
) m
where task1_done = 1
order by id desc
limit 1;
Are these tables related or have any references? if not you can have separate statement and do a union
i.e.
select top 1 column1, column2.. from month1 WHERE task1_done = 1 order by IdentityColumn Desc
union
select top 1 column1, column2.. from month2 WHERE task1_done = 1 order by IdentityColumn Desc
I have to do a complicated delete-statement, that looks like this:
DELETE FROM
(Select t1._id, t1.subject, t1.predicate, t1.object from t1
INNER JOIN t1 AS t2 ON t1.subject=t2.subject
WHERE t2.object='ID20447_325762212'
UNION
Select t1._id, t11.subject, t1.predicate, t1.object from t1
INNER JOIN t1 AS t2 ON t1.object=t2.subject
WHERE t2.object='ID20447_325762212')
SQLitedabatase#delete(Table, selection, selectionArgs) is not useable I think. No way to have Joins and Unions.
SQLiteQueryBuilder has JOINs with setTables(joinString) and UNIONs with subQuery() and Unionquery, but only for selectqueries not delete.
How does it work?
[update]
I could reduce complexity by separating both subqueries in two delete-statements, but there is a join in everyone so thats not a solution. And that's not working either.
[update2]
Here's a screenshot from rows of my table i want to delete.
In my app I have an object with ID...2328 (row 2) and a property(relation) represented by the rows in that screenshot. The relation is targeting to an object with id ...212 . I have to delete that object and all Properties
You can use complex selections in subqueries.
In the general case, it would look like this:
DELETE FROM SomeTable WHERE _id IN (SELECT _id FROM ...complex query...)
However, this particular query isn't very complex after all:
DELETE FROM t1
WHERE subject = (SELECT subject FROM t1 WHERE object = 'ID20447_325762212')
OR object = (SELECT subject FROM t1 WHERE object = 'ID20447_325762212')