Reputation: 3181
I'm trying to write up a subquery
in order to retrieve a client name
from the clients
table by using a client_id
from the orders
table.
SELECT client_id, order_id, deadline, state FROM orders GROUP BY order_id
SELECT name FROM clients WHERE id=:client_id
subquery
into the first in order to display final results like the following, adding the name
from the clients
table based on each client_id
from orders
table matching id
from the clients
table:client_id
- from orders
table
order_id
- from orders
table
deadline
- from orders
table
state
- from orders
table
name
- from clients
table
grouped by order_id
from orders
table
Upvotes: 0
Views: 1046
Reputation: 21
SELECT o.client_id,
o.order_id,
o.deadline,
o.state,
c.name
FROM orders o
join clients c on c.id = o.client_id
GROUP BY o.order_id
SQL-92 and earlier does not permit queries for which the select list, HAVING condition, or ORDER BY list refer to nonaggregated columns that are not named in the GROUP BY clause. You'd better use this:
SELECT o.client_id,
o.order_id,
o.deadline,
o.state,
c.name
FROM orders o
join clients c on c.id = o.client_id
GROUP BY o.client_id,
o.order_id,
o.deadline,
o.state,
c.name
Upvotes: 1
Reputation: 777
If I understand you correctly, you need to get second table's name
value in your result set. Then you have to get values from 2 tables. Using subquery is the one solution:
SELECT o.client_id, o.order_id, o.deadline, o.state, c.name
FROM orders o, clients c
WHERE (c.id = o.client_id)
GROUP BY o.order_id;
Upvotes: 1