MySQL select where equal to multiple values - mysql

I have two databases, where I store who is following who and another which stores the posts the user makes.
I want to select all of the people a user is following from the following database and echo out the usernames of those who that user is following and query the posts database for posts of that user.
My problem is what if a user is following multiple users,
I echoed out of the user id's of the people this user is following and I get
44443344330
When I separate each id with commans, I get:
44,44,33,44,33,0,
so let's give that a variable of $user_ids;
$user_ids = "44,44,33,44,33,0, ";
the query:
$get_posts = mysql_query("SELECT * FROM posts WHERE userid = '$user_ids'");
but all it does is show the records of the first user id, 44.
How can I retrieve all of the records for all the users?

The query should be:
SELECT * FROM posts WHERE userid IN (44,44,33,44,33,0)
However, you may have to rethink your data model and make sure it is normalized, so that you can express this construction directly in the databse without echoing into a comma-separated string.
Why do you have two databases? Do you mean two tables?

Maybe you want to use IN
SELECT * FROM posts WHERE userid IN ($user_ids)

Given that you have two tables, not two databases, the easiest way to match multiple values for a specific column would be the following:
SELECT * FROM posts WHERE userid IN (44,44,33,44,33,0)
*A small point that I ran into when doing this. If you are matching to a column that is of type VARCHAR(n), be sure to wrap your matching values in 'single quotes', not "double quotes"
e.g:
SELECT * FROM posts WHERE name IN ('foo','bar','alpha','beta')

Assuming you have two tabels, not databases, and that the table (lets call it "friends") which describes who is following who is like
table friends(
userid
friendid
)
then query to get posts posted by X's friends would be
SELECT
p.*
FROM posts p
JOIN friends f ON(p.userid = f.friendid)
WHERE f.userid = X

$get_posts = mysql_query("SELECT * FROM posts WHERE userid in '($user_ids)'");

$var= str_replace(","," or userid = ","userid =$your_data_from_db");
your myqsl_query = SELECT * FROM posts where $var

Related

SQL query, find the user that does not have bank_account

SQL query, find the user that does not have bank_account
I have two tables, the first one is table bank_customer, and the other is table user.
The table of bank_customer has many columns, including user_id and bank_account.
in table user, I have column id.
not every user has bank_account. so I want to query, users that do not have a bank_account, but it gets hard.
SELECT * FROM users, bank_customers
WHERE NOT users.id=bank_customers.user_id
so how can I query in SQL with this case?
and how to logic that case? for the next case I can find out by myself.
There are a few ways to go about that, but the simplest way would probably be using IN:
SELECT *
FROM users
WHERE id NOT IN (
SELECT user_id
FROM bank_customers
)

MySQL find matching set of rows

I have a cross-reference table that supplies the many-to-many relationship between users and user group tables. It contains two relevant columns: group_id and user_id (surprise, surprise!). When a user wants to create a new group, I want to first check if that set of users already exists as a group.
Essentially I would define the problem as "Given a set of user ids, find any set of rows that match the set of user ids and all share the same group id".
Edit:
I'm looking for the exact set of users, not interesting in seeing in the resultset groups that include those users in addition to other users.
Sample Data
I have the hunch that a subquery is the way to go, but I can't figure out how to arrange it. Any help would be greatly appreciated!
Is this what you want?
select groupid
from usergroups ug
where userid in ($user1, $user2, . . . , $usern)
group by groupid
having count(*) = <n>;
This returns all groups that have the supplied list of users.
If you want the exact set, then:
select groupid
from usergroups ug
group by groupid
having count(*) = sum( userid in ($user1, $user2, . . . , $usern) );
This assumes that groups don't have the same user twice (it is not hard to adjust for that, but the condition becomes more complicated).

How do I select a record from one table in a mySQL database, based on the existence of data in a second?

Please forgive my ignorance here. SQL is decidedly one of the biggest "gaps" in my education that I'm working on correcting, come October. Here's the scenario:
I have two tables in a DB that I need to access certain data from. One is users, and the other is conversation_log. The basic structure is outlined below:
users:
id (INT)
name (TXT)
conversation_log
userid (INT) // same value as id in users - actually the only field in this table I want to check
input (TXT)
response (TXT)
(note that I'm only listing the structure for the fields that are {or could be} relevant to the current challenge)
What I want to do is return a list of names from the users table that have at least one record in the conversation_log table. Currently, I'm doing this with two separate SQL statements, with the one that checks for records in conversation_log being called hundreds, if not thousands of times, once for each userid, just to see if records exist for that id.
Currently, the two SQL statements are as follows:
select id from users where 1; (gets the list of userid values for the next query)
select id from conversation_log where userid = $userId limit 1; (checks for existing records)
Right now I have 4,000+ users listed in the users table. I'm sure that you can imagine just how long this method takes. I know there's an easier, more efficient way to do this, but being self-taught, this is something that I have yet to learn. Any help would be greatly appreciated.
You have to do what is called a 'Join'. This, um, joins the rows of two tables together based on values they have in common.
See if this makes sense to you:
SELECT DISTINCT users.name
FROM users JOIN conversation_log ON users.id = converation_log.userid
Now JOIN by itself is an "inner join", which means that it will only return rows that both tables have in common. In other words, if a specific conversation_log.userid doesn't exist, it won't return any part of the row, user or conversation log, for that userid.
Also, +1 for having a clearly worded question : )
EDIT: I added a "DISTINCT", which means to filter out all of the duplicates. If a user appeared in more than one conversation_log row, and you didn't have DISTINCT, you would get the user's name more than once. This is because JOIN does a cartesian product, or does every possible combination of rows from each table that match your JOIN ON criteria.
Something like this:
SELECT *
FROM users
WHERE EXISTS (
SELECT *
FROM conversation_log
WHERE users.id = conversation_log.userid
)
In plain English: select every row from users, such that there is at least one row from conversation_log with the matching userid.
What you need to read is JOIN syntax.
SELECT count(*), users.name
FROM users left join conversion_log on users.id = conversation_log.userid
Group by users.name
You could add at the end if you wanted
HAVING count(*) > 0

Finding all polls that a specific user hasn't voted on yet

I have a website that displays poll after poll to a register user, and stores his vote in a table.
A simple structure of the database would be as follows (there are much more fields, but they don't contribute much to the question, so I removed them):
Polls(pollId)
Votes(pollId, userId, vote)
Now I want to run a MySql query to select all polls within the 'Polls' table, except for the polls that the current user had already voted on (which could be determined from the 'Votes' table)
Is it possible to make that using a MySql select statement alone, or will I have to select all polls first, and use some Php logic to filter out the ones already voted on by the user?
Thanks in advance!
SELECT *
FROM Pools
WHERE id NOT IN (
SELECT poolId
FROM Votes
WHERE userId = 142
)
Try something like this:
select p.pollid from polls p where p.pollid not in (select v.pollid from votes v where userId = {USERID})

MySQl - update field by counting data in other table

There are two tables. One is users info "users", one is comments info "comments".
I need to create new field "comments" in users table, that contains number of comments of that user. Table "comments" has "user" field with user's id of that comment.
What is optimal way to count number of comments by every user so far?
With php you should write script that selects every user and than count number of his comments and then update "comments" field. It is not hard for me, but boring.
Is it possible to do it without php, only in MySQL?
UPDATE TABLE users SET CommentCount = (SELECT COUNT(*) FROM comments WHERE AuthorUserId = users.id)
Why do you want to store it there anyway?
Why not just show it combined query?
select users.name, count(comments.id) as comment_count
from users
join comments on users.id=comments.user_id
group by users.id
If you want to do it your way then include
update users set comment=comment+1 where id=$user_id
into the script where you store the comment.
And
update users set comment=comment-1 where id=$user_id
into the place where user can delete his comment. Otherwise your data might be out of sync when user adds new commnts and you haven't run the script yet.
Yes, it is possible.
This is called table joining.
You don't add another field to the users table, but to the resulting table.
SELECT users.*, count(comments.id) as num_comments
FROM users,comments
WHERE comments.cid=users.id
GROUP BY users.id
Such a query is what relational databases were invented for. Do not revert it to the plain text file state. There is many reasons to make it that way.
http://en.wikipedia.org/wiki/Database_normalization <-- good text to read