How to get data referenced in another table in one MySQL query - php

I would to select some data from mysql. However, some of the data stored in the table I am querying from are in codes and to get the text description I need to reference that data to another table.
TABLE: persons
SELECT id, first_name, last_name, address_code, customer_type_code
FROM persons
WHERE id = 1001
TABLE: ref_address
SELECT address_name FROM ref_address
WHERE address_code = 123
TABLE: ref_customer_type_code
SELECT customer_type_name FROM ref_customer_type_code
WHERE customer_type_code = 456
How can I combine all three queries together to return id, first_name, last_name, address_name, customer_type_name in one query instead of querying them 3 times like this?

Please read the reference manual for join.
In short, you need to define a relation between your tables (I use aliases just to make things a bit "cheaper" to write):
select p.id, p.first_name, p.last_name, p.address_code, p.customer_type_code
, ra.address_name
, rctc.customer_type_name
from persons as p
-- Join the persons table with the ref_address table,
-- using the address_code column of each table
inner join ref_adress as ra
on p.address_code = ra.address_code
-- Join the persons table with the ref_customer_type_code table
-- using the customer_type_code column of each table
inner join ref_customer_type_code as rctc
on p.customer_type_code = rctc.customer_type_code
where p.id = 1001
Notice that when you use multiple tables in a query it may be useful to define aliases to avoid having to write again and again the full name of the table. Also, it may be a good idea to explicitly specify each field's source table (by alias, if you are using it)

What you're looking for is a JOIN.
In a JOIN, you specify two tables and how they are related to one another. In a single SELECT statement, you can have multiple JOIN clauses.
SELECT
p.id, p.first_name, p.last_name, p.address_code, p.customer_type_code,
a.address_name,
t.customer_type_name
FROM
persons p
JOIN ref_address a
ON p.address_code = a.address_code
JOIN ref_customer_type_code t
ON p.customer_type_code = t.customer_type_code
WHERE
p.id = 1001
This query says that the table persons and ref_address should be linked, or "joined", by the related columns address_code which are available in each table. Same goes with the tables persons and ref_customer_type_code being linked by the columns customer_type_code.

Related

How to join two tables by 5 columns? Sql

I have two tables called customers and wantslist.
I want to join the columns customername, customeraddress , creditlimit , bytitle and byauthor.
How can I write a query that can show those column together in a table?
The first table is customers. It has the columns customeraddress , customername and creditlimit.
The second table is wantslist. It has the columns bytitle and byauthor.
How can I write a query that can join those 5 columns into 1 table?
Without knowing your specific strucutre you would use a SQL query similar to...
SELECT c.customername, c.customeraddress, c.creditlimit, w.bytitle, w. byauthor
FROM customers as c
JOIN wantslist as w on c.customerid = w.customerid
SELECT customers.customername, customers.customeraddress, customer.creditlimit, wantslist.bytitle, wantslist.byauthor
FROM wantslist
INNER JOIN customers
ON *{your matching condition}*;

SQL SELECT Statement for selecting data from two tables using foreign key

I am just tinkering with SQL as I am trying to get into more complex statements. I don't know this qualifies for it or not but please guide how to go about it.
I have looked at JOINS and some question of Multiple Select Statements but unable to understand them correctly.
I have the following two tables:
emp table:
emp_id, name, address, org_id
books table:
id, emp_id, status, org_id
where emp_id in books table is foreign key referencing emp table.
I need to fetch all the records from books table of a particular org. But along with that I need to get all the data of respective employee like name, address along the result.
Please guide me in the right direction.
Thanks
Try this
select B.*,E.name,E.address from books B
inner join employee E
on B.emp_id=E.emp_id
where B.org_id=1;
I took value of of org_id as 1 for test purpose.
SELECT books.id, books.emp_id, books.status, books.org_id, emp.name, emp.address
FROM books
JOIN emp ON emp.emp_id = books.emp_id
WHERE books.org_id = '3'
As the other said, the org_id from emp table makes no sense. You must remove it from the table.
if you want all records from the books table try this
Select b.id,c.emp_id,b.status,e.name,e.address
from emp_table e
Left join books_table b
on(e.emp_id=b.emp_id)
where e.org_id='3' and b.org_id='3'
You can use this query this will gives you all book record with particular org_id along with all employee record
SELECT * FROM emp as e1
LEFT JOIN books as b1 ON e1.emp_id = b1.emp_id WHERE e1.org_id = 'YOUR_ID'
UNION ALL
SELECT * FROM emp as e1
RIGHT JOIN books as b1 ON e1.emp_id = b1.emp_id WHERE e1.org_id = 'YOUR_ID'
The following query should work for you:
SELECT b.id, b.status, b.org_id, e.emp_id, e.name, e.address
FROM Books b LEFT JOIN Employee e
ON e.emp_id = b.emp_id
WHERE b.org_id = 100
This would be the query for org 100.
It appears that your current schema is not normalized very well:
Employee: emp_id, name, address, org_id
Books: id, emp_id, status, org_id
The two tables both store the org_id, which presumably means the same thing.
This query might give you the results you want. You might want to learn more about joins in SQL. A LEFT JOIN gives you all records from one table, and matching records from another.
SELECT books.*,
emp.name AS emp_name,
emp.address AS emp_address,
emp.org_id AS emp_org_id
FROM books
LEFT JOIN emp ON books.emp_id = emp.emp_id
WHERE books.org_id=?
you can use this for all recors both tables :
select * from books
inner join emp on
books.emp_id=emp.emp_id
where books.emp_id=emp.emp_id

SQL structure with JOIN

I'm having some trouble figuring out how I should build my database for this project i'm currently working on. Fishing-related.
I'm just not sure how to set up my tables.
Table 1(ID, username, email etc)
Table 2(fish, weight, length etc)
How do i join these two tables? Should I have a column named ID in the 2nd table aswell? Because I need to know which user uploaded what fish. I'm just not sure how to do that.
Any help is appreciated.
Yes you have to, and that is called Relation Databases this is example
Users (UserID, UserName, Password)
Fish (FishID, UserID, FishName, Length, Weight)
and then you connect them using UserID
select u.UserName, f.FishName, f.Length, f.Weight
from Users u
LEFT JOIN Fish f on (f.UserID=u.UserID)
and if you are looking for specific user then just add at the end
WHERE u.UserID=#UserID
Looking at you're table structure I think it's best to change the id name in table 1 to *user_id* and add a column in the second table also named *user_id*. Joining using the columns is then very simple using the following query:
SELECT *
FROM table1
JOIN table2 USING (user_id)
Other possibility would be to add a column named *user_id* (or something else) to table2 and create a query like:
SELECT *
FROM table1
JOIN table2 ON table2.user_id = table1.id
In this case, you set the columns to use for the join in the 'ON .. = ..' structure.

There are two columns in the new table(table1 join table2) which have the same column name, how to get the values of both respectively

select * from table1 join table2 on table1.column3=table2.column4 where ...
...
$row=mysql_fetch_assoc($result);
However, there are two columns in the new table(table1 join table2) which have the same column name, how to get the values of both respectively?
Call the columsn out specifically with an alias like
SELECT table_1.id as table_1_id, table_2.id as table_2_id
Youll have to list out all or most of the columns form at least one of the tables this way but you can get access to cols with the same name across multiple tables.
Prefix the column name in the select with its table name.
select table1.my_column, table2.my_column
from table1, table2
where table1.id = table2.t1_id
But with this method, you would have to read the columns using their returned order indexes, rather than their names. Another answer mentioned using as to name each column, so consider that if you're going to read them by name.
When there's a column name collision due to a query joining 2+ tables, you can not use *. You can use:
SELECT table_1.*,
table_2.*
FROM table_1,
table_2
If that doesn't return the list of columns you want, you will have to explicitly list every column. There's no way around - it's an all or nothing deal.
Table Aliases
...but typing out the full table name every time can be a pain, which is why you can alias tables:
SELECT t1.*,
t2.*
FROM table_1 AS t1,
table_2 t2
Either alias notation is supported. They're also required if you want to join a table to itself.
Using only the column names in a Select list that you actually need\ is always the best, but when you want everything, then, well, go ahead and use the *:
Select a.*,
b.*,
a.id as a_id,
b.id as b_id,
a.name as a_name,
b.name as b_name
from tablea a,
tableb b
...
It won't hurt to be redundant, as a.* includes a_id and a_name, but there values from the * get lost in the associative array, so just put them back in with new, unique names.

Retrieving MYSQL Join values from PHP

I have two or more tables which hold values under the same column name. Now when I join these two tables the column names stay the same. When retrieving these values in PHP ($row['name']) I encounter problems since the column 'name' is used twice.
Are there any possible means of separating these two columns inside the query?
SELECT *
FROM stories s
JOIN authors a ON a.id = s.authorid
Table stories
id, name, content, date
Table authors
id, name, date
When i join these two i get one table with similar 'name' columns.
Is there anyway to separate the two tables so the author table has a prefix in front of it? E.g. authors_name /authors_*
Yes, change your SQL this way :
SELECT
s.Id as StoryId,
s.Name as StoryName,
a.Id as AuthorId,
a.Name as AthorName,
FROM stories s
JOIN authors a ON a.id = s.authorid
Then in php, use StoryId, StoryName, AuthorId and AthorName instead of Id or Name.
Hope it helps you.
Yes there is!
SELECT *, stories.name AS s_name, authors.name AS a_name
FROM stories s
JOIN authors a ON a.id = s.authorid
And there you have it. All fields plus two extra! ;)
Hope it helps.
Sorry you can't really do prefixing on a field level, but if you can call 2 queries, just use
SELECT s.*
FROM stories s
JOIN authors a ON a.id = s.authorid
The result set will only contain stories fields and you can use the fields as you normally would with php. Then just do the same again for authors.

Categories