mysql SELECT WHERE and SELECT again - mysql

I have two tables Customers and Customer_orders. I'm trying to SELECT customer's order by using Customer_ID from Customer table.
SELECT * FROM Customer_orders WHERE Customer_ID = SELECT ID FROM Customers WHERE Customer_name = 'John Doe'
This code does not work. How do I do this?

You need to JOIN those 2 tables and then query for what you need. Like this:
SELECT co.*
FROM Customer_orders co
INNER JOIN Customers c ON co.Customer_ID = c.ID
WHERE c.Customer_name = 'John Doe';

The other answer is a little complex - it might attempt to show you a solution that can solve a more difficult problem.
First, it queries the ID of the John Doe from Customer table.
Second, it queries the all columns from Customer_orders table where customer_id equals ID.
My solution is easy:
SELECT * FROM Customer_orders WHERE Customer_ID in (SELECT ID FROM Customers WHERE Customer_name = 'John Doe')
or
SELECT * FROM Customer_orders WHERE Customer_ID = (SELECT ID FROM Customers WHERE Customer_name = 'John Doe')
Generally, ID is a primary key of Customer table and the customer_id should be a key index of the Customer_orders.
Two times query of single table using key index is faster than the query using join operation especially when the tables have too many rows.
And thanks Tim to correct my grammar. I so appreciate it. My English is not good .

you can use join method (inner / left) or even subquery (but not recommend to use this on this problem)
here example
inner join
SELECT cust_order.* FROM Customer_orders cust_order, Customers cust WHERE cust_order.Customer_ID = cust.ID AND cust.Customer_name = 'John Doe'
left join
SELECT cust_order.* FROM Customer_orders cust_order LEFT JOIN Customers cust ON cust_order.Customer_ID = cust.ID WHERE cust.Customer_name = 'John Doe'
sub query
SELECT * FROM Customer_orders WHERE Customer_ID = (SELECT ID FROM Customers WHERE Customer_name = 'John Doe')
make sure you only have 1 ID on table Customers if you want to use sub query, or if it have more than 1 ID, you can use "IN" instead of "="

Related

How to perform inner join for this query

Can someone help me trouble shoot my syntax i spent 1 hour on it yet i cant figure it out.
I have 3 tables:
**Student**
-ID (UUID)
email (String)
**Teacher**
-ID (UUID)
email (String)
**StudentTeacher**
-ID (UUID)
studentId (UUID)
teacherId (UUID)
I have an initiate query which returns some studentId
SELECT studentId FROM TeacherStudents WHERE teacherId IN ('123', '456') GROUP BY studentId HAVING COUNT(DISTINCT teacherId) = 2
I would like to join the results with Students table so i can return the email address
However, this is not working
SELECT email FROM TeacherStudents WHERE teacherId IN ('123', '456') GROUP BY studentId HAVING COUNT(DISTINCT teacherId) = 2 INNER JOIN Students on TeacherStudents.studentId = Students.id
It returns an error.
The correct syntax is:
SELECT s.studentId, s.email
FROM TeacherStudents ts JOIN
Students s
ON ts.studentId = s.id
WHERE ts.teacherId IN (123, 456)
GROUP BY s.studentId, s.email
HAVING COUNT(DISTINCT ts.teacherId) = 2 ;
Notes:
WHERE is a SQL clause that follows the FROM clause.
JOINs are an operator in the FROM clause.
TeacherId is probably a number, so do not use single quotes.
Table aliases make the query easier to write and to read.
You are learning SQL, so be sure the unaggregated columns in SELECT match the GROUP BY. You can drop s.studentId from the SELECT if you really want to.
Qualify all column names so you know what table they come from.
The generalised case, to get all columns from the Student table...
SELECT
Students.*
FROM
(
SELECT studentId
FROM TeacherStudents
WHERE teacherId IN ('123', '456')
GROUP BY studentId
HAVING COUNT(DISTINCT teacherId) = 2
)
StudentsOfInterest
INNER JOIN
Students
ON StudentsOfInterest.studentId = Students.id

MySQL - Return the last record on the second table then return all in the first table

I have two tables customers and orders, below is the structure.
Table - contacts
id
Table - orders
id
contact_id
How can I select all from contacts table but only select the latest record from the orders table?
SELECT contacts.*,
Max(orders.id)
FROM contacts
LEFT JOIN orders
ON contacts.id = orders.contact_id
GROUP BY contacts.id;
But I always gets NULL if I use LEFT JOIN, it only have value if I use INNER JOIN.
select the latest record in orders and group it first
select contacts.*, orders.id
from contacts
left join (select max(id) as id, contact_id
from orders
group by contact_id) orders
on contacts.id = orders.contact_id
You can try to use UNION like
select * from orders order by id desc limit 1
UNION
select * from contacts
In order to aggregate max value with all columns from contacts table, add all columns from contacts table after group by function
I trust the answer provided by Alex should work well. The following query shall list all records from contacts and the last id from orders table.
SELECT
c.*,
(SELECT Max(o.id) FROM orders o
INNER JOIN contacts c1 ON o.id=c1.id
)as last_order_id
FROM contacts c

How do I select two tables in 1 query?

I want to select two tables in one query but it doesn't seem to work. I have tried nested select but I just got sql_error:
Subquery returns more than 1 row
Here is my query:
SELECT `client`.`id` as client_id,
(SELECT `org`.`name` FROM `org`) as organization
FROM `client`
What is the better way to query two tables?
Here is my expected result:
client_id = [1,2,3,4,5]
organization = [x,y,z]
This will work but it isn't what you want i think.
SELECT `client`.`id` as client_id, `org`.`name` as organization FROM `org`, `client`
This will give you a cross product of all rows in org with all rows in client. Maybe you want something like this:
SELECT `client`.`id` as client_id, `org`.`name` as organization FROM `org` JOIN `client` ON `client`.`memberOf` = `org`.`id`
The JOIN will connect rows of both tables where column memberOf in table client is equal to column id in table org
You should use join queries to join two or more tables. you can visit https://dev.mysql.com/doc/refman/5.0/en/join.html
Example of the join query:
SELECT t1.name, t2.salary
FROM employee AS t1 INNER JOIN info AS t2 ON t1.name = t2.name;

Single query instead of multiple select statements

Hello I am stuck in a SQL statement situation. Can anyone help me with the statement:
Table 1.
Customers
customer_id | customer_name | custom_url | customer_desc
Table 2.
Categories
category_id | customer_id | category_name
select customer_id where category_name="Realtor";
gives me a list of customer ids. Now I use them to find all their names, desc and url from the customers table.
I need to do this in a single query and process the customer details to display on the UX. I am really stuck how to do this.
Here is what i have (which I know is wrong)
select * from customers where customer_id = Loop (select customer_id from categories where category_name="Realtor");
Modify your query to a JOIN query like
select c.*
from customers c
join categories ca on c.customer_id = ca.customer_id
where ca.category_name='Realtor';
You can do what you want using IN or ANY or EXISTS:
select *
from customers
where customer_id = ANY (select customer_id
from categories
where category_name = 'Realtor'
);
Or:
select *
from customers
where customer_id IN (select customer_id
from categories
where category_name = 'Realtor'
);

mysql query result issue with join

I have multiple tables as table_1 has id , p_code, profile_status, name and table_2 has id, p_code, availablity and table_3 has id, p_code, status...
How to get all records form all tables depend on p_code.
table_2 and table_3 has few records. if p_code not in table_2 and table_3 then echo 'no' in results.
currently i am using my query as below
select t.id, t.p_code,t.name,t.num_rooms, t.profile_status, t.distance FROM (
( SELECT id , p_code, profile_status, name,num_rooms, 3956 * 2 * ASIN(SQRT( POWER(SIN(($origLatAirport - latitude)*pi()/180/2),2)
+COS($origLatAirport*pi()/180 )*COS(latitude*pi()/180)
*POWER(SIN(($origLonAirport-longitude)*pi()/180/2),2)))
as distance FROM property WHERE profile_status=1 having distance < ".$dist." ) ) as t
How to add table_2 and table_3 and fetch results.
Pleasr reply soon. I am stuck here.
In your query you are doing CROSS JOIN and what you desire, is probably INNER JOIN.
In MySQL the CROSS JOIN behaves like JOIN and INNER JOIN of without using any condition.
The CROSS JOIN returns all rows form user multiplied by all rows from user_inbox - for every user you get inboxes of all users.
You should specify condition for your JOIN statement.
$sql_alt = mysql_query(
"select i.*,u.images, u.firstname, u.lastname
from user_inbox i INNER JOIN user u ON i.to_id = u.user_id
where i.to_id = '$user_id'");
Also it is good habit have the same names for primary and foreign keys, so I think you should have user_id or user_id_to instead of to_id in your user_inbox table. This is of course not absolutely necessary.