Join two table from MySQL database - php

I need to join table accounts and table users from my MySQL database.
$sql = "SELECT id FROM `".DB_ACCOUNTS."` WHERE `id` IS NOT NULL ";
table accounts and table users contain a same column as id. I want to get gender, birthday from users and bodybuild, weight, height, ethnictype, skincolor from accounts.
Users Table
Accounts table:
How to do this? Please help.

SELECT US.gender, US.birthday,AC.bodybuild, AC.weight, AC.height, AC.ethnictype, AC.skincolor
FROM accounts AC
INNER JOIN users US ON AC.ID=US.ID
You can try above code.
It will helps you.

$sql = "SELECT u.gender, u.birthday, a.bodybuild, a.weight, a.height, a.ethnictype, a.skincolor
FROM accounts a
LEFT JOIN users u on a.id = u.id
WHERE a.id IS NOT NULL ";
please try above query...

Change id column in User table with userid.after that you must add userid at Accounts table as Foreign Key. userid column at Account table contain userid value from User table.
ALTER TABLE Accounts
ADD FOREIGN KEY (userid) REFERENCES Users(userid);
sql = "SELECT u.gender,u.birthday,ac.bodybuild, ac.weight, ac.height, ac.ethnictype, ac.skincolor
FROM Users u
LEFT JOIN Accounts ac
ON u.userid=ac.userid
WHERE ac.userid IS NOT NULL; ";

Related

How would this SQL join work?

I have two tables, "Users" and "Jobs".
Users Table:
UserID
Username
Password
AccountType
Forename
Surname
ContactNumber
EmailAddress
Jobs Table:
JobID
JobTitle
JobDescription
JobLocation
JobDate
JobStartTime
JobPay
PostedDate
PostedBy
AcceptedBy
JobStatus
I want to display all of the job rows, and the Username, ContactNumber and EmailAddress from the users table where the "AcceptedBy" in the jobs table is the same as the "UserID" from the users table.
Try this query
SELECT * FROM Jobs INNER JOIN Users ON Jobs.AcceptedBy = Users.UserID
I'll show you other example and try to do with your example
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID=Customers.CustomerID;
here is the tutorial
enjoy :)

Mysql inner join/ multiple selects in one query?

Hi all!
I'm scripting a guestbook (personalized for each user). I have one table for users and a different one for the guestbook. Now, the way I'm currently displaying the name of the author of a post is not optimal. I simply have a row in the DB for "fromname" i.e the authors name.
I would like to select the authors name based on the authors ID and matching that to their name in the "users" table.
So... This is my mysql query right now:
$sql = " SELECT
pid,toid,fromid,message,fromname,name,pdate,flag
FROM gbook INNER JOIN users
ON id='{$_GET['id']}'
WHERE toid='{$_GET['id']}'
ORDER BY pdate DESC";
I guess I need to like... Select the name on a different condition but in the same query. But I don't know how.
I hope you understand my problem.
Help will be greatly appreciated!
/Jafool
Assuming your users table has a column called username, the following should do what you want:
SELECT
pid,
toid,
fromid,
message,
u.username,
name,
pdate,
flag
FROM gbook INNER JOIN users u
ON id='{$_GET['id']}'
WHERE toid='{$_GET['id']}'
ORDER BY pdate DESC"
All I did was alias the user table (as u), and refered to u.username instead of the fromname you had before.
From what I am seeing it looks like you need to link to the users table twice since you have a fromid and a toid. If you have a users table, why would you have a fromname field in the gbook table? Anyway if my assumption is correct then you may be interested in the following query:
SELECT g.*, u1.username AS ToUser, u2.username AS FromUser
FROM gbook AS g
INNER JOIN users AS u1 ON u1.id = g.toid
INNER JOIN users AS u2 ON u2.id = g.fromid
WHERE g.toid = '{$_GET['id']}'
ORDER BY g.pdate DESC
Hard coding the name in the guestbook table is indeed dirty. Assuming your table structure is something like this:
users( id, name )
gbook( pid, toid, fromid, message, fromname, name, pdate, flag )
your query is already almost ok. Just change it as follows to select all columns of both tables:
$sql = " SELECT *
FROM gbook g INNER JOIN users u
ON u.id=g.fromid
WHERE toid='{$_GET['id']}'
ORDER BY pdate DESC";
Then you can display the name with something like
$result = mysql_query($sql);
while( $val = mysql_fetch_array($result) )
{
$username = $val["u.name"];
}

How to create a contacts page properly?

I want to do a contacts page. Here is my table structure:
Accounts Table:
1) id
2) User_id
3) Full_name
4) Username
5) Email
6) Password
Contacts Table:
1) My_id (This is the user who added friend_id)
2) Contact_id (this is the contact who was added by my_id)
3) Status
My query looks something like this:
$sid = ID of user who is viewing;
$sql = "SELECT STRAIGHT_JOIN DISTINCT contacts.contact_id,
accounts.full_name FROM contacts INNER JOIN accounts
on contacts.contact_id = accounts.user_id WHERE
contacts.my_id = '$sid' OR contacts.contact_id = '$sid'";
The problem is that it doesn't work the right way. I end up seeing my name in the query (meaning when i login i see my name in the contacts instead of contacts name).
How to fix this? Thanks.
The STRAIGHT_JOIN keyword should not be necessary here. To get the contact information, use a second JOIN to the contacts table which relates it back to the accounts.
SELECT
DISTINCT c.contact_id,
cn.full_name
FROM
accounts a
/* first join connects the adding user's id to records in contacts */
INNER JOIN contacts c ON a.user_id = c.My_id
/* second join connects contact list user ids back to names in accounts */
INNER JOIN accounts cn ON cn.user_id = c.Contact_id
WHERE a.User_id = '$sid'
This query ought to suffice:
SELECT DISTINCT contacts.contact_id, accounts.full_name
FROM contacts, accounts
WHERE (contacts.my_id = '$sid' AND contacts.contact_id = accounts.user_id)
OR (contacts.contact_id = '$sid' AND contacts.my_id = accounts.user_id)

contactlist mysql query

Im making a codeigniter webapp where users can add each other in a contactslist.
The table looks like this:
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_1` int(11) NOT NULL,
`user_2` int(11) NOT NULL,
`accepted` tinyint(2) NOT NULL,
PRIMARY KEY (`id`)
The userid for the user that makes the request to add the contact is always stored in user_1 column. The other users userid is stored in user_2. user_2 then has to accept the request and the 'accepted' column gets updated to 1.
I want to list all contacts that are accepted (WHERE accepted = 1) in a html table, and the contact requests (accepted = 0) in another.
My question is: How can i make a mysql query that selects all the rows and just get the userid from the contact? Its a problem since they can be in either user_1 or user_2 (Depending on if they requested or accepted).
Should i change the db table in some way to achieve this. Or could i make a query (active rcords preferably) that accomplish this?
Any help is appreciated
Thanks in advance
George
Update:
So the final query looks like this:
SELECT DISTINCT users.id, users.username, contacts.accepted
FROM users
LEFT JOIN contacts ON users.id = contacts.user_1
WHERE contacts.user_2 = ' . $this->session->userdata('user_id') . '
UNION DISTINCT
SELECT DISTINCT users.id, users.username, contacts.accepted
FROM users
LEFT JOIN contacts ON users.id = contacts.user_2
WHERE user_1 = ' . $this->session->userdata('user_id')
And works exactly as i described :)
Use a UNION query. See the documentation.
SELECT DISTINCT user_1 userid FROM user WHERE accepted = 1
UNION DISTINCT
SELECT DISTINCT user_2 userid FROM user WHERE accepted = 1
About the join, you'd use something like below for each part of the UNION
SELECT DISTINCT users.userid, users.username, contacts.accepted
FROM users
LEFT JOIN contacts ON users.userid = contacts.user_1
WHERE contacts.user_2 = ?
Shouldn't the contactlist be owned by the user?
create table Contactlist (
OwnerID int, -- ID of the owning User
ContactID int, -- ID of the contact User
Accepted bool)
-- With composite primary key on OwnerID, ContactID
This way the query would be
select * from User
left outer join Contactlist on User.ID = Contactlist.OwnerID
left outer join User as Contact on Contactlist.ContactID = Contact.ID
Sorry... Overthunk the select ;)
select * from Contactlist
inner join User on Contactlist.ContactID = User.ID
where Contactlist.OwnerID = <the querying users ID>
(MSSQL syntax)
You can use queries but it will create problems later on I guess as I have also faced this problem before. You can insert new entries in the same table when a user accepts the request and mark the new record as accepted but this time the user_1 becomes user_2 and vice versa.
Alias with joins is waht I think you are asking.
Something like.
Select c.id, uRequest.UserName, uRequested.UserName From Contacts c
inner join Users As uRequest On c.User_1 = uRequest.id
inner join Users As uRequested On c.User_2 = URequested.id
Where accepted = 1
will give you all contacts where the request has been accepted.

PHP: WHERE in another table

Yes so im building an query from the advanced search form.
I have this:
$query = "SELECT * FROM users WHERE 1 ";
$query .= "AND sex = '$sex' ";
for now, next im going to have AND birthday.. but then i dont know how to do it, because users birthday is stored in users_profile
So please correct me, how can i:
$query .= "AND birthday in users_profile = '1'";
Is this possible even, or should i reconstruct it and put birthday in users instead..
update:
in users, the id column there, is binded with users_profileĀ“s uID.
So in users_profileĀ“s uID column, there is the users id.
I assume your users_profile table is linked to the users table?
SELECT u.*, up.birthday
FROM users u
INNER JOIN users_profile up
ON u.user_id = up.user_id
WHERE sex = '$sex'
Here an Inner Join is used. The reason we can use u instead of users and up instead of users_profile is because we have set up the aliases "users u" and "users_profile up"
You need to look at the syntax for JOIN.
You need a way to join individual related rows in the two tables, something like:
SELECT u.* FROM users u, users_profile p
WHERE u.sex = 'M'
AND p.birthday = '1'
AND u.userid = p.userid;
I don't understand why you have separate tables for user and for users_profile, but you need to JOIN the two tables:
SELECT U.*
FROM users U
LEFT JOIN users_profile P
ON P.uID = U.uID
AND P.birthday = '1'
WHERE U.sex = '$sex'
Very possible, given you have the foreign key to the users_profile table.
Let's say the primary key in the users table is named 'id', and the users_profile table contain a field called 'uid' which point to the users table, you'd normally create the query like this:
SELECT * FROM users u, users_profile p WHERE u.id = p.uid
AND u.sex = '$sex' AND u.birthday = 1

Categories