MySQL Query 2 Tables in 1 - php

I am having a problem writing a MySQL query to get data from 2 tables in the same database. I don't know how to combine the 2 tables into 1 table basically so that I can use PHP to display the information. Right now I am using 2 queries and PHP to join them... I really need the persons name and the score they got.
tbl_scores
----------
user_id
points
tbl_users
---------
user_id
name
tbl_users has more fields but those are the only ones that matter I think? Please help or send what I need to look up to learn more.

SELECT * FROM tbl_scores RIGHT JOIN tbl_users ON tbl_scores.user_id = tbl_users.user_id;

The word you're looking to use is JOIN... more information on MySQL JOINs can be found all over the internet but I found one here: http://mysqljoin.com/
The following code is untested but should work for your scenario...
SELECT
u.name,
s.points
FROM
tbl_users AS u LEFT JOIN tbl_scores AS s ON u.user_id = s.user_id

use Join and more specificaly Left Join because it returns all rows from the left table (tbl_users ), even if there are no matches in the right table (tbl_scores) so that you get all users even those with no score :
SELECT * FROM tbl_users LEFT JOIN tbl_scores ON
tbl_users.user_id = tbl_scores.user_id;

Related

Want to select data from different tables

I have two tables in database, named users(store user details) and posts(store post details). Now i want to get data from both tables. Like user_image from users and post description from post.
I am using this query
SELECT * FROM `users`AS u,`posts` WHERE u.user_id IN (SELECT user_id FROM `posts`)
But it returns duplicate data. I have 2 users and 3 posts but it returns 6 posts.
Try something like:
Select a.user_image, b.post_description from users as a join posts as b on a.user_id = b.user_id
Do an inner join & you shall get the desired result
In the above query a & b are alias for the two different tables. I you do not want to use alias you can also write it as users.user_image in your select statement.
Write the fields you want from both the tables in your select statements.
The below image will help you understand the inner join
Inner Join Circle for understanding
Use group by as below:
SELECT * FROM `users`AS u,`posts` WHERE u.user_id IN (SELECT user_id FROM `posts`) group by u.user_id
What about
Select * FROM user u right join posts p on u.id = p.user_id
?
if you want to get data from both tables you need to use joins.and you make sure the two tables are interlinked by primary keys
so use this can help
select user_image,post_description from users join posts on users.user_id=posts.user_id;

How to join all three tables in MYSQL?

I have a MySQL database that has three tables holding information about uploaded photos by users. I have a PHP page that displays all the photos in the database (tbl_uploads) and who uploaded them (tbl_users). To display the photos and who uploaded them I have a join in the MySQL query.
SELECT *
FROM tbl_uploads, tbl_users
WHERE tbl_uploads.user_id = tbl_users.user_id
ORDER BY date DESC
I now want to join a third table tbl_collab to the MySQL query that allows me to display all the users that collaborated with the photo (a form allows them to post the $file and their $user_id to tbl_collab). I guess I need to add a join from tbl_uploads.file with tbl_collab.user_id but I'm not sure how.
tbl_users
|//**user_id**//|int(11)|No|
|user_name|varchar(25)|No|
|user_email|varchar(60)|No|
|user_password|varchar(255)|No|
|joining_date|datetime|No|
tbl_uploads
|//**id**//|int(10)|No|
|file|varchar(100)|No|
|type|varchar(30)|No|
|size|int(11)|No|
|user_id|int(11)|No|
|user_name|varchar(25)|No|
tbl_collab
|//**id**//|int(11)|No|
|user_name|varchar(100)|No|
|user_id|int(11)|No|
|file|varchar(255)|No|
I have been trying your various suggestions and I can't really get them to work as I would hope so I have made a mysql fiddle that might be help me.
The problem is that when I loop through the rows that the query throws up in PHP I ether get just the rows where there is join with tbl_uploads.file and tbl.collab.file or I get the multiple rows duplicating themselves.
I'd suggest preferring ANSI SQL syntax for joins (over mentioning multiple tables in the "from" clause) as once the queries get complex I find the ANSI syntax easier to follow. Using that syntax, joining multiple tables is no big deal. e.g.,
SELECT uploads.<column>, users.<column>, collabs.<column>
FROM tbl_uploads uploads
JOIN tbl_users users ON users.user_id=uploads.user_id
JOIN tbl_collabs collabs ON collabs.file=uploads.file
ORDER BY uploads.date DESC
(Note, replace <column> above with the names of columns you want to select from the respective tables, using AS syntax to provide unique names where necessary.)
Consider that you will probably want to create indexes over the fields in the join conditions for performance if you expect the database will become large. You may also want to use left joins when joining, e.g., tbl_collabs if it is possible an upload will have no collaborators, otherwise the query will return no data if there are no matching rows in tbl_collabs.
The first thing to do is to normalize your data. If you look closely, username appears in all three tables. It shouldn't. It belongs only in the users table. Then your other tables need to have a user_id field instead of the username.
tbl_uploads
|//**id**//|int(10)|No|
|file|varchar(100)|No|
|type|varchar(30)|No|
|size|int(11)|No|
|user_id|int(11)|No|
tbl_collab
|//**id**//|int(11)|No|
|user_id|int(11)|No|
|file|varchar(255)|No|
In both cases the user_id is a foreign key to the id field in the users table. Now we have something consistent to join on.
SELECT * FROM tbl_uploads
INNER JOIN tbl_users ON tbl_uploads.user_id = tbl_users.user_id
INNER JOIN tbl_collab ON tbl_collab.file = tbl_uploads.file
Whether you should use INNER JOIN or LEFT JOIN depends on exactly what you need to do with your data, but INNER JOIN seems more appropriate based on information provided.
Update: As #drew pointed out, none of your tables have a column named date did you perhaps intend to sort by tbl_users.joining_date?
Seems the join is on file to me
SELECT *
FROM tbl_uploads
inner join tbl_users on tbl_uploads.user_id = tbl_users.user_id
inner join tbl_collab on tbl_collab.file = tbl_uploads.file
ORDER BY date DESC
You can just add another join condition. Also, note that implicit joins (having multiple tables in the from clause) isn't considered a good practice, and you should probably use explicit join clauses:
SELECT *
FROM tbl_uploads up
JOIN tbl_users us ON up.user_id = us.user_id
JOIN tbl_collab c ON c.user_id = up.user_id
ORDER BY date DESC

How to transfer a lot of values beteen tables in a variable or array?

I have two SQL tables. The first one structure is simple.
ID Name
----------
The second one is simple too.
CommentID Comment CreatorID
----------------------------------
I want to show in my site all the comments that correspond with the "ID of user"
The problem is we have here a lot of ID and two different tables.
Something like this:
$1= $bdd->query("SELECT * FROM comments WHERE id_user=220281");
$2=$1->fetch();
But its impossible because id user is not on the comments table.
The most simple way to do this is to join the tables like this:
select
users.name,
comms.commentID,
comms.comment
from
userTable users
join commentTable comms
on users.ID=comms.ownersID
where
users.id=1
This will return the users name in each row of data, but you don't need to use it in the output more than once.
It also sounds like you could use a few pointers on SQL queries. Do yourself a favour and have a read of this article I put together a while back.
SELECT c.*
FROM comments c
INNER JOIN users u ON c.id_creator = u.id_user AND
u.id_user = 220281
A simple join will do the trick like this :
SELECT c.comment, u.user_name FROM
Users u
JOIN
Comments c ON
c.creator_id = u.user_id
WHERE
u.user_id=220281
fiddle:http://sqlfiddle.com/#!6/3b28a/1

php/mysql join syntax

I have the userids of people who have joined a group in one table but not their names thatlie in another table. So I think I need to do a join. I'm starting with groupid that describes the grouop.
Table 1, groupmem has groupid and userid for the members.
Table 2, users has userid and username
The users table has every user. The groupmem only has some who have joined groups.
SQL statement should be something like following but can't get it to work.
select users.name
FROM users,groupmem
LEFT JOIN users
on groupmem.userid=users.userid
WHERE groupmem.groupid = 22
22 being some value..
Thinking maybe where clause is in wrong place or I am using wrong type of join but or not using on correctly but, in any case, can't get it to work. Thx for any suggestions:
Try:
SELECT u.username
FROM `users` u
LEFT JOIN `groupmem` g
ON u.userid = g.userid
WHERE g.groupid = 22
This should do the trick:
SELECT users.name
FROM groupmem
LEFT JOIN users ON groupmem.userid = users.userid
WHERE groupmem.groupid = 22
Your query seems to be quite right - assuming I guessed your table-structure right.

SQL Joins across multiple tables

I am building an online survey system for which I wish to produce statistics. I want query based on the gender of the user. I have the following tables:
survey_question_options
survey_answer
users
I have constructed the following query so that it brings back a null response where there are no answers to the question:
SELECT COUNT(sa.option_id) AS answer , so.option_label
FROM survey_answer sa
RIGHT JOIN survey_question_options so
ON sa.option_id = so.option_id AND
sa.record_date>='2011-09-01' AND
sa.record_date<='2012-08-01'
LEFT JOIN users u
ON (sa.uid = u.uid AND u.gender='F')
WHERE so.question_id=24
GROUP BY so.option_label
ORDER BY so.option_id ASC
My query returns the following results set:
0 Red
1 Yellow
0 Blue
0 Green
However, the gender condition in the LEFT JOIN appears to be ignored in the query. When I change the gender to 'M' the same result is returned. However, the expected result would be 0 for everything.
I am not sure where I am going wrong. Please help.
Thanks in advance.
Well, you are doing a COUNT on a column from the main table, so the gender condition on the LEFT JOIN won't affect the result. You should do the COUNT on a column from the users table. I'm not sure if this is what you want, but you should try:
SELECT COUNT(u.uid) AS answer , so.option_label
FROM survey_answer sa
RIGHT JOIN survey_question_options so
ON sa.option_id = so.option_id AND
sa.record_date>='2011-09-01' AND
sa.record_date<='2012-08-01'
LEFT JOIN users u
ON (sa.uid = u.uid AND u.gender='M')
WHERE so.question_id=24
GROUP BY so.option_label
ORDER BY so.option_id ASC
The left join to the users table is evaluated after the join to the answer table - so although the user record is not returned if the user is the wrong gender, the answer record will be returned (regardless of the user's gender). Try:
SELECT COUNT(sa.option_id) AS answer , so.option_label
FROM (select a.option_id
from survey_answer a
JOIN users u ON a.uid = u.uid AND u.gender='F'
where a.record_date>='2011-09-01' AND
a.record_date<='2012-08-01') sa
RIGHT JOIN survey_question_options so
ON sa.option_id = so.option_id
WHERE so.question_id=24
GROUP BY so.option_label
ORDER BY so.option_id ASC
You're putting your condition in the wrong block. Since you're performing a LEFT JOIN, (which is a left-bound outer join) everything in the left table (the main table) is selected, together with the data from the joined table, where applicable. What you want is to add the data from all users and then restrict the full output of the query. What you've actually done is add the user data from only the female users and then displayed all data.
Sounds technical, but all you have to do is move the AND u.gender='F' into the main WHERE clause instead the ON clause. That will cause SQL to only select the rows for female users after the JOIN has taken place.

Categories