SQLite Select with join from the same parent - sqlite

I have two simple tables:
Names:
+----+-------------+
| id | Name |
+----+-------------+
| 1 | John Smith |
| 2 | Joe Doe |
+----+-------------+
Relations:
+----+----------+---------+
| id | ParentID | ChildID |
+----+----------+---------+
| 1 | 1 | 2 |
+----+----------+---------+
The table relation, Parent is Foreign Key to Names and Child is Foreign Key to Names.
Is there a way to SELECT and replace ParentID and ChildID with Name from Names where number matches Names.id?

You can join with the same table multiple times, as long as you give each instance a unique name:
SELECT Parent.Name,
Child.Name
FROM Relations
JOIN Names AS Parent ON Relations.ParentID = Parent.ID
JOIN Names AS Child ON Relations.ChildID = Child.ID;
Alternatively, simply use subqueries:
SELECT (SELECT Name FROM Names WHERE id = Relations.ParentID) AS ParentName,
(SELECT Name FROM Names WHERE id = Relations.ChildID ) AS ChildName
FROM Relations;

Related

SQLite UPDATE Value Using Foreign Key Reference

Given three tables with one table serving as a junction table which contains two foreign key columns, I'm trying to make an insert so that, given a TableA.prefix, TableA.number, TableB.prefix, and TableB.number, I can update the JunctionTable.is_archived column for the matching row in JunctionTable:
So while the matching row in JunctionTable currently looks like:
+----------------------------------------------------------------------+
| id | tblA_id | tblB_id | is_archived |
| 3 | 7 | 98 | 0 |
+----------------------------------------------------------------------+
And matching rows in TableA and TableB look like:
TableA
+----------------------------------------------+
| id | prefix | number |
| 7 | CLA | 754 |
+----------------------------------------------+
TableB
+----------------------------------------------+
| id | prefix | number |
| 98 | RED | 221 |
+----------------------------------------------+
I'd like to UPDATE the is_archived value like so:
+----------------------------------------------------------------------+
| id | tblA_id | tblB_id | is_archived |
| 3 | 7 | 98 | 1 |
+----------------------------------------------------------------------+
I've tried a few different statements based on information found here but they aren't valid:
UPDATE JunctionTable
SET is_archived = "1"
WHERE tblAid =
(SELECT id FROM TableA WHERE prefix = "CLA" AND number = 754)
AND tblB.id =
(SELECT id FROM TableB WHERE prefix = "RED" AND number = 221)
UPDATE JunctionTable
SET is_archived = "1"
WHERE (
LEFT JOIN TableA ON JunctionTable.tblA_id=TableA.id
WHERE TableA.course_prefix = "CLA" AND TableA.course_number = 754
LEFT JOIN TableB ON JunctionTable.tblB_id=TableB.id
WHERE TableB.course_prefix = "RED" AND TableB.course_number = 221)
In the first query, it looks like the problems are the names of the ID columns in your Junction table ("tblAid" and "tblB.id"), and you're using double quotes instead of single quotes. This should work:
UPDATE JunctionTable
SET is_archived = 1
WHERE tblA_id =
(SELECT id FROM TableA WHERE prefix = 'CLA' AND number = 754)
AND tblB_id =
(SELECT id FROM TableB WHERE prefix = 'RED' AND number = 221)

SQL Query for Parent Child Data from two table

I have 2 table one table is Course Category and second is Course
In Course Category Table
Following data stores :
CategoryId | Name
1 | MCA
2 | MBA
In Course Table
Following data stores :
Id | Name | CategoryId | ParentId
1 | Asp.Net | 1 | 0
2 | C# | 1 | 1
3 | Finance | 2 | 0
i want following output
Id | Name | Parent
1 | MCA | 0
2 | MBA | 0
3 | Asp.Net | 1
4 | C# | 3
5 | Finance | 2
Whether i have to use nested query or should i relate two tables with foreign and primary keys or any mapping should be done.if not give me a solution to do this.
thanks in advance
select rownum as id, name, 0 as parent
from Category
union all
select rownum, name, id
from course
I assume that you only have one level of children (no cases like parent<-child<-child)
select c.id, t.name, parent.name, c.name from course c
join category t on c.categoryId = t.id
left join (select c2.id, c2.name from course c2) parent on c.parentId = parent.id
This should give you something like
id |categoryname |parentname |coursename
1 |MCA |null |Asp.Net
2 |MCA |Asp.Net |C#
3 |MBA |null |Finance
This is not exactly your desired result but should do the trick to display what you want.

How to Display doctors ordered by number of performed surgeries

I have table [Surgery_By] table[Surgery] table[Doctor] i'm using ASP.NET with SQL Server :
The table [Surgery_By] contains the following columns:
1-ID (PK)
2-Surgery ID (FK)
3-Doctor ID (FK)
How to Display doctors ordered by number of performed surgeries ?
Try it this way
SELECT d.id, d.fullname, COUNT(s.id) total_surgeries
FROM doctor d LEFT JOIN surgery_by s
ON d.id = s.doctor_id
GROUP BY d.id, d.fullname
ORDER BY total_surgeries DESC
Sample output:
| ID | FULLNAME | TOTAL_SURGERIES |
|----|------------|-----------------|
| 1 | John Doe | 3 |
| 2 | Jane Doe | 1 |
| 3 | Mark Smith | 0 |
Here is SQLFiddle demo
This is a stab in the dark.
Select Doctor.ID As DoctorID
,Count(*) As Count
From Doctor
Join Surgery_By
On Doctor.ID = Surgery_By.DoctorID
Group By Doctor.DoctorID
Order By Count(*)
I am not sure if you want the table Surgery incorporated (but if you do, the join will be pretty straight forward - just be sure to add selected columns to the Group By statement.)
From ASP.NET, you may select this data from a SQL Command.

Query to get the user list which are belongs to a group

I can select the users which has 'sex = 2' by this sql
createQueryBuilder('s')
->where('s.sex = 2');
How can I select the users which are belonging to group A?
My tables are below.
my user table.
ID | name |sex
1 | bob |1
2 | kayo |2
3 | ken |1
my fos_group table
ID | name
1 | student
2 | teacher
my fos_user_user_group
user_id | group_id
1 | 1
2 | 2
3 | 1
it means that
Bob and Ken are belonging to group_1(student)
Kayo is belonging to group_2(teacher)
I would like to select the lists from user table which are belonging to 'student' or 'teacher'
What I want to have is username list belonging to student.
ID | name | sex
1 | bob |1
3 | ken |1
You need to do a join first, and then filter on the association property.
$entityRepository
->createQueryBuilder('s')
->join('s.groups', 'g') // Assuming the association on your user entity is 'groups'
->where('g.name = :group')->setParameter('group', 'student');
See http://docs.doctrine-project.org/en/2.0.x/reference/dql-doctrine-query-language.html#joins for examples of filtering on associations with DQL.
SELECT
g.name AS GroupName,
GROUP_CONCAT(u.name) AS Users
FROM fos_group AS g
INNER JOIN fos_user_user_group AS ug ON ug.group_id = g.ID
INNER JOIN user AS u ON u.id = ug.user_id
GROUP BY g.name
OUTPUT :
GroupName | Users
---------------------------
student | bob , ken
teacher | kayo

How to add a new column in a View in sqlite?

I have this database in sqlite (table1):
+-----+-------+-------+
| _id | name | level |
+-----+-------+-------+
| 1 | Mike | 3 |
| 2 | John | 2 |
| 3 | Bob | 2 |
| 4 | David | 1 |
| 5 | Tom | 2 |
+-----+-------+-------+
I want to create a view with all elements of level 2 and then to add a new column indicating the order of the row in the new table. That is, I would want this result:
+-------+------+
| index | name |
+-------+------+
| 1 | John |
| 2 | Bob |
| 3 | Tom |
+-------+------+
I have tried:
CREATE VIEW words AS SELECT _id as index, name FROM table1;
But then I get:
+-------+------+
| index | name |
+-------+------+
| 2 | John |
| 3 | Bob |
| 5 | Tom |
+-------+------+
I suppose it should be something as:
CREATE VIEW words AS SELECT XXXX as index, name FROM table 1;
What should I use instead of XXXX?
When ordered by _id, the number of rows up to and including this one is the same as the number of rows where the _id value is less than or equal to this row's _id:
CREATE VIEW words AS
SELECT (SELECT COUNT(*)
FROM table1 b
WHERE level = 2
AND b._id <= a._id) AS "index",
name
FROM table1 a
WHERE level = 2;
(The computation itself does not actually require ORDER BY _id because the order of the rows does not matter when we're just counting them.)
Please note that words is not guaranteed to be sorted; add ORDER BY "index" if needed.
And this is, of course, not very efficient.
You have two options. First, you could simply add a new column with the following:
ALTER TABLE {tableName} ADD COLUMN COLNew {type};
Second, and more complicatedly, but would actually put the column where you want it, would be to rename the table:
ALTER TABLE {tableName} RENAME TO TempOldTable;
Then create the new table with the missing column:
CREATE TABLE {tableName} (name TEXT, COLNew {type} DEFAULT {defaultValue}, qty INTEGER, rate REAL);
And populate it with the old data:
INSERT INTO {tableName} (name, qty, rate) SELECT name, qty, rate FROM TempOldTable;
Then delete the old table:
DROP TABLE TempOldTable;
I'd much prefer the second option, as it will allow you to completely rename everything if need be.

Resources