I have a basic query that fetches values from three tables. The three tables : company, classes_by_company, and person. I have a foreign key in all tables with the name company_id. In the where clause I am using LIKE to compare with a random value the values fetched for any results that may have a match. But I am having no success in doing so. I get an error in the sql line WHERE a.id LIKE %1% OR a.company_id LIKE %3% OR c.count LIKE %1% OR p.count LIKE %1%. How can I compare all the values fetched from these three tables against a random value to see if there is a match? SQLFIDDLE
SELECT a.id, a.company_id, a.status,
c.count AS classes_per_company,
p.count AS employees_per_company
FROM company a
LEFT JOIN (SELECT company_id, COUNT(*) as count
FROM classes_by_company
GROUP BY company_id) c
ON a.company_id = c.company_id
LEFT JOIN (SELECT company_id, COUNT(*) as count
FROM person
GROUP BY company_id) p
ON a.company_id = p.company_id
WHERE a.id LIKE %1% OR a.company_id LIKE %3% OR c.count LIKE %1% OR p.count LIKE %1%
Table Schema:
CREATE TABLE company
(
id int auto_increment primary key,
company_id int,
status varchar(20)
);
CREATE TABLE classes_by_company
(
id int auto_increment primary key,
company_id int,
class_name varchar(20)
);
CREATE TABLE person
(
id int auto_increment primary key,
employee_id int,
company_id int,
person_name varchar(20)
);
LIKE has to be followed by a string, so it should be:
WHERE a.id LIKE '%1%'
OR a.company_id LIKE '%3%'
OR c.count LIKE '%1%'
OR p.count LIKE '%1%'
id is an integer column; the LIKE operator relies on a text data type e.g. nvarchar.
You could convert the id to a string e.g. WHERE CAST(a.id AS VARCHAR(10)) LIKE '%1%' ...
Please also note the single quotes around the %1%.
Related
Two tables
Customer_Fixed_Deposit(
ID int primary key,
name varchar(20),
Fixed_Deposit int
);
Customer_Loan(
ID int primary key,
name varchar(20),
Loan int
);
I want the ID of all the customers and with names in both the tables without using set operations
I tried to insert all the values of id and name in 1 table into another, because there were duplicates and ID is the primary key it did not work
You can get all customers with the same name, assuming names are unique.
SELECT fd.id, fd.name, l.id, l.name
FROM Customer_Fixed_Deposit fd
JOIN Customer_Loan l
ON fd.name = l.name;
Now, if you want to insert only those customers to Customer_Loan table who are not already present in it.
INSERT INTO Customer_Loan (name)
SELECT name
FROM Customer_Fixed_Deposit
WHERE NOT EXISTS (
SELECT fd.id
FROM Customer_Fixed_Deposit fd
JOIN Customer_Loan l
ON fd.name = l.name;
);
If I understand you correctly, you have two tables with two different sets of people and IDs? If so, then I think a UNION would allow you to select all the IDs and Names from each table into one result. Try this:
SELECT
ID, name
FROM
Customer_Fixed_Deposit
UNION
SELECT
ID, name
FROM
Customer_Loan;
I wanna a query to get first_name of students and first_name of teachers which have the most courses with each other with the number of these courses.
Table Student:
CREATE TABLE Student(
id INT AUTO_INCREMENT,
first_name VARCHAR(255) NOT NULL,
last_name VARCHAR(255),
email VARCHAR(255) UNIQUE,
PRIMARY KEY (id)
);
Table Teacher:
CREATE TABLE Teacher(
id INT AUTO_INCREMENT,
first_name VARCHAR(255) NOT NULL,
last_name VARCHAR(255),
email VARCHAR(255) UNIQUE,
degree VARCHAR(10) NUT NULL,
PRIMARY KEY (id)
);
Table Course:
CREATE TABLE Course(
id INT AUTO_INCREMENT,
code INT NOT NULL UNIQUE,
name VARCHAR(255) NOT NULL,
st_id INT,
teach_id INT,
PRIMARY KEY (id),
FOREIGN KEY st_id REFERENCES Student (id),
FOREIGN KEY teach_id REFERENCES Teacher (id)
);
Is the below query correct? i.e. Can I use 3 SELECT in a query?
query1:
SELECT S.first_name
FROM Student AS S
INNER JOIN Course AS C
ON C.st_id = S.id
SELECT T.first_name
FROM Teacher AS T
INNER JOIN Course AS CC
ON CC.teach_id = T.id
SELECT COUNT(*)
FROM Course
WHERE Course.st_id = S.id
AND Course.teach_id = T.id
GROUP BY COUNT(*)
ORDER BY DESC;
query2:
SELECT S.first_name, T.first_name, COUNT(*)
FROM Student AS S, Teacher AS T, Course
WHERE Course.st_id = S.id
AND Course.teach_id = T.id
GROUP BY COUNT(*)
ORDER BY DESC;
If the above queries are not correct(probably the first one is wrong) guide me to correct answer, please.
NOTE: If the ordering isn't unique, order by the name of teachers first, then order by the name of the students(for clarity but not important so much to me).
Your second query is closer to being right but it has some issues. I would recommend using JOIN statements rather than implied joins. This makes the query easier to read.
Something like this should work:
SELECT t.first_name,
t.id,
s.first_name,
s.id,
COUNT(*) AS course_count
FROM Course c
JOIN Student s ON c.st_id = s.id
JOIN Teacher t ON c.teach_id = t.id
GROUP BY t.id, s.id
ORDER BY course_count DESC, t.first_name, s.first_name;
You need to add a group by in order to get your count on a per student basis. Putting the group by on the id columns rather than the name makes sure you get counts on unique students and teachers in case you have multiple records in your table with the same first name. I am also adding the id columns to the select for the same reason, but these are not necessary and can be removed without affecting the accuracy of the query.
SELECT t.first_name, t.id, s.first_name, s.id, COUNT(c.id) AS course_count
FROM course c
JOIN student s ON c.st_id = s.id
JOIN teacher t ON c.teach_id = t.id
GROUP BY t.id, s.id
ORDER BY t.first_name, s.first_name
The essential data is contained in the Courses table, with the Student and Teacher tables only required for gathering the names. This query joins the 3 tables in question, computing the count of courses shared by teachers and students.
When execute my query i just get 1 item back that i attached to the sellerId instead of 2. Does anyone know how i can say?
select the name of item and re seller for each item that belongs to the re seller. With a rating higher than 4?
Current Query:
SELECT items.name, sellers.name
FROM items
inner JOIN sellers
on items.id=sellers.id
WHERE rating > 4
ORDER BY sellerId
The query for tables inc. data:
CREATE TABLE sellers (
id INTEGER NOT NULL PRIMARY KEY,
name VARCHAR(30) NOT NULL,
rating INTEGER NOT NULL
);
CREATE TABLE items (
id INTEGER NOT NULL PRIMARY KEY,
name VARCHAR(30) NOT NULL,
sellerId INTEGER REFERENCES sellers(id)
);
INSERT INTO sellers(id, name, rating) values(1, 'Roger', 3);
INSERT INTO sellers(id, name, rating) values(2, 'Penny', 5);
INSERT INTO items(id, name, sellerId) values(1, 'Notebook', 2);
INSERT INTO items(id, name, sellerId) values(2, 'Stapler', 1);
INSERT INTO items(id, name, sellerId) values(3, 'Pencil', 2);
You've got the wrong join, here's a corrected query;
SELECT items.name, sellers.name
FROM items
inner JOIN sellers
on items.sellerId=sellers.id
WHERE rating > 4
ORDER BY sellerId
You're joining on id = id, you want sellerid = id
Notice in your table definition that item.sellerId is the field that joins to seller.id
CREATE TABLE items (
id INTEGER NOT NULL PRIMARY KEY,
name VARCHAR(30) NOT NULL,
sellerId INTEGER REFERENCES sellers(id)
);
You need to join on the correct column:
SELECT i.name, s.name
FROM items i INNER JOIN
sellers s
ON i.sellerid = s.id
----------^
WHERE rating > 4
ORDER BY i.sellerId
Note that I also introduced table aliases and qualified column names. These make a query easier to write and to read.
SELECT items.name, sellers.name
FROM items, sellers
WHERE items.sellerId = sellers.id and sellers.rating>4;
Here is the right query:
SELECT items.name as items, sellers.name as sellers
FROM sellers
INNER JOIN items
ON (sellers.id = items.sellerid)
WHERE sellers.rating > 4
I have two table in two different database.
Kalix2 -->I have one table ph_Companies
Asterisk--> Here I have table called cdr.
In ph_Companies I am having CompanyName column and company name is in this format.
CompanyName
AccuWebHosting
In other table I am having another column clid which stores the company name in the following format.
clid
"AccuWebHosting-EN" <6618083563>
Now, my question is how can I make join between these two table based on this column. In both the table these are the only column which is having some common data. No other column is having similar data.
Please help me. Thanks in advance.
SELECT a.*, b.*
FROM ph_Companies a
INNER JOIN otherTable b
ON b.clid LIKE CONCAT('%', a.CompanyName, '%')
Caution, this query is very slow if you want large database because it requires a FullTable Scan. The reason is you have "bad" schema design. I'll recommend you to alter the tables like this,
CREATE TABLE ph_Companies
(
ID INT PRIMARY KEY,
CompanyName VARCHAR(20),
-- OTHER COLUMNS HERE
);
CREATE TABLE otherTable
(
ID INT AUTO_INCREMENT PRIMARY KEY,
CompanyID INT,
CompanyName VARCHAR(20),
clid VARCHAR(50),
-- OTHER COLUMNS HERE
CONSTRAINT tb_fk FOREIGN KEY (CompanyID)
REFERENCES ph_Companies (ID)
);
and you will have a query like this,
SELECT a.*, b.*
FROM ph_Companies a
INNER JOIN otherTable b
ON a.ID = b.CompanyID
which is FAR more better than the query above.
Given the table creation SQL and insertion SQL, How will I generate a query to display the information in a a particular way?
CREATE TABLE cities (
id serial NOT NULL UNIQUE PRIMARY KEY,
iname varchar(100) NOT NULL UNIQUE
)
CREATE TABLE suburbs (
id serial NOT NULL UNIQUE PRIMARY KEY,
icity integer REFERENCES cities (id),
iname varchar(100) NOT NULL UNIQUE
)
CREATE TABLE type (
id serial NOT NULL UNIQUE PRIMARY KEY,
iname varchar(100) NOT NULL UNIQUE
)
CREATE TABLE sale (
id serial NOT NULL UNIQUE PRIMARY KEY,
iname varchar(100) NOT NULL UNIQUE
)
CREATE TABLE estate (
id serial NOT NULL UNIQUE PRIMARY KEY,
icity integer REFERENCES cities (id),
isuburb integer REFERENCES suburbs (id),
itype integer REFERENCES type (id),
isale integer REFERENCES sale (id),
idescription text,
itimestamp timestamp DEFAULT CURRENT_TIMESTAMP
)
INSERT INTO cities (iname) VALUES ('Johannesburg');
INSERT INTO suburbs (icity, iname) VALUES (1, 'Westbury');
INSERT INTO type (iname) VALUES ('Room');
INSERT INTO sale (iname) VALUES ('Rent');
INSERT INTO estate (icity, isuburb, itype, isale, idescription) VALUES (1, 1, 1, 1, 'A Nice place in a real bad neighbor hood');
Now I want the numerical values that are in the table estate to be displayed by the string values that they represent.
E.G
1 Johannesburg, Westbury, Room, Rent, Description
What will the SQL Query be for this, I am more concerned in using postgreSQL.
you cany try like
select * from table1
inner join table2 on tabl1.pk = table2.FK
inner join table3 on tabl1.pk = table.FK
Final
select table2.iname,table3.iname,table4.iname,table1.idescription
from estate as table1
inner join sale as table2 on table1.isale = table2.id
inner join type as table3 on table1.itype = table3.id
inner join suburbs as table3 on table1.isuburb = table3.id
inner join cities as table4 on table1.icity = table4.id
If you want to get info about joins have look to below image
Ans at : How do I decide when to use right joins/left joins or inner joins Or how to determine which table is on which side?
First, they must have some sort of common field. Let's assume the common field between them is called <tablename>_ID; the way you do it is as follows:
select A.colx, A.coly, A.colz, B.colx, B.colw, c.cold
from A inner join B on A.ID=B.A_ID
inner join C on C.A_ID=A.ID
select suburbs.icity
, cities.iname
, suburbs.iname
, type.iname
, sale.iname
, estate.idescription
from estate
inner join suburbs on suburbs.id = estate.isuburb
inner join cities on cities.id = estate.icity
inner join type on type.id = estate.itype
inner join sale on sale.id = estate.isale
In general, you are looking for a join..
select ct.iname as CityName,sb.name as SuburbName,et.*
from estate et
join cities ct on ct.id=et.icity
join suburbs sb on sb.id=et.isuburb
etc...
You could do it this way :
SELECT *
FROM A
INNER JOIN B
ON B.id = A.b
INNER JOIN C
ON C.id = A.c
Check this example as per ur ques.
SELECT A.*,B.*,C.*
FROM A , B, C
WHERE C.c = B.b
AND B.b = A.a
-> select * from estate
-> inner join cities on estate.icity=cities.id
-> inner join suburbs on estate.isuburb=suburbs.id
-> inner join type on estate.itype=type.id
-> inner join sale on estate.isale=sale.id;