I am trying to figure out best way to compare results from 2 queries and display the difference.
Table 1 = User Table
Table 2 = Page Table
Table 3 = Assigned table
Example:
There are users 1 and users 2 in the user table.
User 1 has been assigned to 10 pages, user 2 has been assigned to only 1 page.
This works fine for finding which pages they have assigned, which is only 1 page for this example.
SELECT * FROM assigned_table WHERE user= 2
But I can not figure out how to get results of all the other pages it doesn't have access to.
This does not work because there is user 1 that has access to all 10, so it gets the results of all other users except user2
SELECT * FROM assigned_table WHERE user != 2
So basically I need it to say what pages does user2 have access to, and then which pages does it not have access to and display both results separately
Any assistance would be appreciated.
Sorry if similar topic was posted elsewhere, was unable to find what I was looking for.
You should use a join for this. Here's the documentation on this https://dev.mysql.com/doc/refman/5.0/en/join.html.
Something like
select pt.pagename from `Assigned table` as at
join `Page Table` as pt
on at.pageid = pt.id
where at.user = 2
This would give you a listing of all page titles (pagename) user 2 has assigned to him/her. Your column and table names will need to be updated.
Pull all papers not assigned to specific user.
select pagename
from `Page Table`
where id not in (select pageid from `Assigned table` where at.user = 2)
Related
I'm trying to build a MySql query to produce results based on following:
Table Permissions
user_id blog_id
=========================
1 1
1 2
1 3
2 2
3 1
Table Blog
id name
=========================
1 First Blog
2 Second Blog
3 Third Blog
4 Fourth Blog
I need to select all the records from Blog table and display it based on logged in user id like:
$user_id = $_SESSION['user_id];
Table Permissions contains access for each user allowed to view results from blog table.
So something like:
"SELECT * FROM Blog WHERE id IN()"
but I'm not sure how to access permission table to use it in IN().
So for example if user with id 1 is logged in, this user should be able to see Blogs with matching id's 1,2 and 3.
You can use either a join, or an in() subquery.
select b.* from blogs b
inner join permissions p
on b.id=p.blog_id
where p.user_id=...
Try this:
SELECT * FROM Blog INNER JOIN Permissions ON Permissions.blog_id = Blog.id
This show all users.
Working code here: http://sqlfiddle.com/#!9/aa3e9/14
You can use:
SELECT * FROM Blog INNER JOIN Permissions ON Permissions.blog_id = Blog.id
WHERE Permissions.user_id = 'user_id number'
To get a specific user.
Scenario
I have three elements in this problem. One is an array of ids in this format: (1,3,5,6,8). That array is a list of id of users I want to display. The second element is table that contains user information something simple like: id name surname email. The third element is a second table that contains users configuration. There are two parameters in that last table, one is lid, and the other is usraction (among others, but the important are those two). lid represent a permission type and usraction the value, if the user wants his data to be public there will be a row on that table where lid=3 and usraction="accepted", also I register the datetime of the action every time the user changes this permission, so each time he change it a new row is added, and in order to retrieve the actual state of the permission i have to retrieve the last row for the user an check the value of usraction like this:
SELECT * FROM legallog WHERE uid = '.$user['id'].' AND lid = 3 ORDER BY ABS(`registration` - NOW()) LIMIT 1
Then in php:
if($queryresult && $queryresult[0]['usraction']=='accepted') //display data
The problem
In the scenario id described how im getting the actual state of the permission set by one user at the time, the problem now is I want to sort of clean an array of ids in one or two sql calls. Lets say I want to print the user information of 4 users, one function gives me the ids in this format: (2,6,8,1), but those users may not want to display their information, using the query I showed before I can make a call to the sql server for each user and then generate a new array, if the users who authorize are 1 and 8 the result array will be (8,1).
The think is whit an array of 100 users I will make 100 calls, and I dont want this, is there a way to solve this in one or two querys?
A query such as this gets you the information you want:
select u.*,
(select usraction from configuration c where c.userid = u.userid and c.lid = 3 order by datetime limit 1
) as lastLid3Action
from users u
where u.userid in (1,3,5,6,8)
If you only want "accepted" values, then make this a subquery:
select t.*
from (select u.*,
(select usraction from configuration c where c.userid = u.userid and c.lid = 3 order by datetime limit 1
) as lastLid3Action
from users u
where u.userid in (1,3,5,6,8)
) t
where LastLid3Action = 'Accepted'
As I understand you have two tables in the first table, where the user information is stored; and the second table, where the user permission is stored. And you want to get information from the first table using permission from the second table, then you need this query:
SELECT a.*
FROM first-table-name AS a
RIGHT JOIN second-table-name AS b a.uid = b.lid
WHERE uid in (1,3,5,6,8) AND usraction='accepted'
ORDER BY ABS)
LIMIT 1
You question is somewhat vague, but if you are asking how to select a number of records when you have a list of ids, the answer is:
select column, list, goes, here from tablename
where id in (1,5,8,12,413);
That will get you the values of the columns you list for just the records that match your array of ids.
Hi friends i am listing topics in php which may be associated with multiple category
my db schema is
topics
topic_id
user_id
topic_name
category
category_id
category_name
topic_category (for association)
tc_id
topic_id
category_id
topic_response // for results
tr_id
topic_id
response ( given in a form of 5 star rating so its in range of 1-5 always )
user_id
what i need to do is
1st ) list top ten topics based on responses ya it will be based on count of responses
i tried ->
select t.* ,count(tr.response) as votes from topics t , topic_response tr where t.topic_id=tr.topic_id group by tr.topic_id order by votes LIMIT 10
not working
2nd) user will be shown list of topic . he can choose the category in which he wants that can be multiple too.
for example
if he chooses category_id 1,2,3,4 then topics listed in this category will be listed.
i have tried to
select t.* from topics t ,topic_category tc where tc.topic_id = t.topic_id and category_id IN (1,3,2,4)
// not able to get idea on this i would prefer if i could do this in subquery since i also need to check if the user has already responded to that question .
**3) in case if i get a query working suppose .
from php side i will be getting an array of category_id from select multiple dropdown
like array(1,2,3,4)
so i was thinking how will make this query accept category id
in form of category_id IN (1,3,2,4) in mysql query**
**can i directly pass an array like
category_id IN ($ids) where $ids is an array**
i am a newbie in mysql please help me
you help will be appreciated :)
For the first question:
You have to use LEFT JOIN and match (response's topic id row) to (topic's id) then count(response's topic id) and GROUP everything by (response's topic id).
for example:
Responses Table = responses
response_id
topic_id
response_message
Topics Table = topics
id
title
content
The query is
SELECT topics.title,topics.content,COUNT(responses.topic_id) AS count FROM topics
LEFT JOIN responses ON topics.id = responses.topic_id GROUP BY count LIMIT 10
For question 2:
You can try using AND ( IN 1 OR 2 OR 3 OR 4
You can try using BETWEEN 1 AND 4
WHERE(category_id>=1&&category_id<=4)
Okay, so I want to have a news feed on my website. I have 3 tables named Users, Follow, and Posts. Basic user data goes into the Users table, who is following who is stored in the Follow table, and whatever the user posts goes into Posts. Now, I know how to select every post from a database table and limit it using the WHERE clause. But how would I write my query to select all all of the posts from only user's they are following, and display them by DESC date? Thanks.
Here's a general layout for you, make three tables like you mentioned, I've outlined below just as an example
[TABLES]
users
followers
posts
In the users table you should have at least columns like userid (auto incremented value / primary key).
The followers table should have something like userid which would match to the users table userid, a followid column which would also have the id # for the follower from the users table.
Then for your posts table you would want to have userid too so when each post is made it would have the id from users table.
Then you would need to do something like:
SELECT p.*
FROM posts AS p
WHERE p.userid IN (SELECT followid FROM followers WHERE userid = ###)
ORDER BY p.date DESC
Now it really depends on how you are getting the users id to figure this out. If your passing the users id using a session after they logged in similar to something like Facebook, then you could change userid = ### to something like userid = ".$_SESSION['userid']." But again it really depends on how you pass the users id but the above should at least get you somewhat started.
Make sure to put indexes on the userid, followid columns so that when the table becomes larger it will do the joins quickly.
An alternative to #Shane's answer is to use the JOIN operator:
'SELECT p.* // I prefer to name all the fields, but for brevity's sake I'll use the shorthand
FROM Posts AS p
INNER JOIN Follow AS f ON p.userid = f.followid
WHERE f.userid = '.$selectedUserID.'
ORDER BY p.date DESC;'
For an inputed User ID ($selectedUserID), it will find all User ID's of the people they follow (matching follow ID to user ID on the Follow x-ref table) and then find their respective posts from the Post table in descending order by date. It will return empty if they do not follow anyone or the people they follow have no posts.
I also hope I do not need to remind you to sanitize your input to the database and escape your output to the web.
Is this what you're looking for?
Let me set up the situation first.
I have a "users" table with X fields, the fields dont really matter for my question except for "visibility". Visibility is a tinyint and the values mean the following (0 = visible to all, 1 = visible to friends only, and 2 = invisible).
I also have a friends table (id, user_id, target_user_id). user_id is friends with target_user_id. Easy enough so far right?
Here is where it gets sticky. Im writing a PHP API and my class method looks kinda like this:
public function getUsers($requester, $page, $num) {}
the $requester is the user id of the person requesting the users
the $page is the pagination page number
the $num is the number of items per page
What I want to do in SQL is get $num users from the users table if their visibility field is = 0 or 1. If the visibility flag is 1 however, I need to make sure the user id and the $requester are friends in the friends table and only return that user if they are friends.
I thought about using PHP to filter the visibility after I get my results back but the pagination (limit) will be screwed up if I ask for 5 records for example and one or more user has visibility set to 1 and are not friends with the requester. This pretty much has to be done entirely thru sql.
Possible??
Try creating a temp table 'temp' with same structure as users.
select * into temp From users where visibility=0 or visibility=1;
Select * from temp, friends where (temp.visibility=0) or (temp.user_id = friends.target_user_id);
Don't forget to empty the temp table.
I haven't tried the second query yest, let me know what output you got.
select * from users, friends where (users.visibility=0) or (users.visibility=1 and users.user_id = friends.target_user_id);
I think you can use LEFT JOIN for this.. something like
"SELECT *
FROM users t1
LEFT JOIN friends t2 ON t2.user_id=t1.id AND t1.visibility=1
INNER JOIN user t3 ON t3.id=t2.target_user_id
WHERE t1.visibility=0 OR t1.visibility=1
LIMIT ".($page*$num).",".$num