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;
Related
I'm not too good with explaining things, apologies.
I have 3 tables that are similar to the below:
users
id
username
threads
id
title
user_id
lastpost_id
posts
id
content
thread_id
user_id
On a page listing forum threads, I want the username of both the thread author, and the last post author of that thread to be displayed, I'm attempting to achieve this in a single query.
My query looks like this:
SELECT t.*,u.username FROM threads t
INNER JOIN users u ON t.user_id=u.id
INNER JOIN posts p ON t.lastpost_id=p.id
ORDER BY t.id DESC
The first join enables me to get the username of the user id that started the thread.
The second join is what I'm not sure on, it can get me the user id but how do I get the username from that, as a 3rd join?
You can select the same table multiple times if you give it a different alias. You can give the fields aliases too:
SELECT
t.*,
tu.username as threadusername, /* Result field is called 'threadusername' */
p.*,
pu.username as lastpostusername
FROM threads t
INNER JOIN users tu ON t.user_id=tu.id /* thread user */
INNER JOIN posts p ON t.lastpost_id=p.id
INNER JOIN users pu ON p.user_id=pu.id /* post user */
ORDER BY t.id DESC
You can join to a joined table like this:
SELECT t.*,u.username,u2.username FROM threads t
INNER JOIN users u ON t.user_id=u.id
INNER JOIN posts p ON t.lastpost_id=p.id
INNER JOIN users u2 ON p.user_id=u2.id
ORDER BY t.id DESC
Note, I haven't had time to test it, but it should work (at least in MySQL).
I don't know if I got it correctly, but as per my understanding you can have a inner query to fetch the thread ids and then have a outer query to fetch the posts based on the thread id, have a max on post id and group by user id. Also join to user to have the name. Hope that helps.
Hi I am trying to change some code so that users with certain group id do not show in search results.
at the moment the code is
$query = 'SELECT distinct b.'.$db->nameQuote('id')
.' FROM '.$db->nameQuote('#__users').' b';
I am trying to add something like the following but cannot get it to work.
select * from '.$db->quoteName('#__users').' where id not in (select user_id from #__user_usergroup_map where group_id = 8)
Any help would be appreciated.
Thanks.
This how you can try
select * from users u
where
not exists
(
select 1
from user_group ug
where
u.id = ug.iduser
AND ug.group_id = 8
)
You need change the table name and field name in the above query as your need.
DEMO
There are three ways of doing that.
Method 1: Join
Join usergroup_map table and then, select all rows that have different group_id that way:
SELECT <comma separated fields> from USERS u
LEFT JOIN USERGROUPS ug ON u.user_id = ug.user_id
WHERE ug.group_id != :group_id
GROUP BY u.user_id
And then -> bind any number to :group_id.
Please keep in mind that above statement will return users that are assigned to :group_id only if they are in another groups as well. (one to many relation).
Method 2: Subselect
Already suggested by other users.
Method 3: Join & Subselect
The 3rd, and the last option is to use sub-query within join statement, which tends to be the fastest solution in terms of optimalization. Of course, query times may be different depending on the engine you are working with, but it's worth giving a try.
SELECT <comma separated fields>
FROM USERS u
INNER JOIN (
SELECT g.user_id
FROM USERGROUPS g
WHERE g.group_id != :group_id
) ug ON ug.user_id = u.user_id
--
In this answer, I assume that you have properly configured database with foreign keys.
I would like to select the posts from users based on who the logged in user is following. What would I need to do? How do I use two different tables with one SELECT statement? I don't even know where to start.
I have 3 tables:
users
posts
followers
Thanks.
SELECT p.*
FROM followers f
JOIN posts p
ON p.author = f.following_id
WHERE f.user_id = $logged_in
ORDER BY
p.post_date DESC
I had to make up the field names as you haven't provided them.
Selecting from two tables is done using JOINs
http://dev.mysql.com/doc/refman/5.0/en/join.html
basically you select from two tables and define JOIN condition.
Assume you have two tables:
users with columns: user_id, user_name, online_state
posts with columns: post_id, user_id (user who posted this post), title, message
SELECT p.title, p.message FROM users u JOIN posts p ON u.user_id = p.user_id WHERE u.online_state = 'online'
join condition should be after ON, non-join condition after WHERE
I would go with the Join query as Quassonoi suggested in his answer, If you want to try an alternate solution, you can do it with subquery like this
SELECT P.PostId,P.Title,P.Body
FROM Post P WHERE P.CreatedById
IN (
SELECT FollowerID from Followers WHERE USER_ID=3
)
Replace 3 with the current user id. Assuming your table structure is something like this.
POST
PostId (int)
Title
Body
Followers
UserId (int)
FollowerId (int)
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;
So, I understand how the relationships work in mysql but I'm having a hard time figuring out how its implemented in my code.
For example, say I have the 3 tables.
Table 1: users - user id, username, user city
Table 2: categories - category id, category name
Table 3: user_categories - user id, category id
If I were to query the database for every user that was in a particular city and list them out with the all of the categories they belong to... How would I do this? Would I need to loop through the results and do a separate query for each user, then list the results? Or, is there some magic query that will return a multidimensional array?
I believe the above would be many-to-many, correct me if I'm wrong....
EDIT In the user_categories table, a user can contain more than 1 category, I'm trying to figure out how to return all of them
Thanks!
You're absolutely right, it is a many-to-many query.
And from what I understand, what you're looking for is the ability to have some kind of hierarchical result to display, meaning for one user, have an array of all the categories he's assigned to...
Couple of things you could do:
Option 1: Query the users table:
SELECT u.user_id, u.username, u.user_city WHERE city = 'somecity';
From the results, get all the user_id's that match, put them in an array.
array(1,3,4,5)
Then execute a query by joining the 2 tables categories and user_categories, and passing the array as a comma separated list in a where in:
SELECT user_categories.user_id, categories.category_name
FROM user_categories INNER JOIN categories ON user_categories.category_id = categories.category_id
WHERE user_categories.user_id IN (1,3,4,5)
This will give you a list of user-id, category name that you can use in your script with the previous results to build your result set
option 2: my preferred, use MySQL's GROUP_CONCAT(http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat).
SELECT users.user_id, users.user_name, GROUP_CONCAT(categories.category_name) AS categories
FROM users
INNER JOIN user_categories ON users.id = users_categories.user_id
INNER JOIN categories ON user_categories.category_id = category.id
WHERE user.user_city = 'somecity'
GROUP BY user.user_id
This will return something like:
user_id username categories
1 u1 cat1, cat2, cat3
2 u2 cat1, cat3
You can specify the separator by using SEPARATOR in group_concat.
You need to JOIN the tables.
If I were to query the database for every user that was in a particular city and list them out with the all of the categories they belong to
SELECT *
FROM users
INNER JOIN user_categories
ON (user_id)
INNER JOIN categories
ON (category_id)
WHERE ...
You could try:
SELECT u.user_id, u.username, u.user_city, c.category_id, c.category_name
FROM users u
INNER JOIN user_categories uc ON u.user_id = uc.user_id
INNER JOIN categories c ON uc.category_id = c.category_id
WHERE u.user_city = 'Cityname';
I haven't tested this, and there might be a more efficient way to do it, but it should work.
If you are unfamiliar with joins in mysql, check this out.