I'm trying to join together two tables, but I cannot get the results I want to get.
So the results I'm looking for is that, I want to be able to "echo" out all the Topic where a user has been involved, by either creating the topic och making a post/comment inside the topic.
I've tried something like:
SELECT *
FROM Topics
LEFT JOIN Posts ON Topics.topic_creator = 'AAAA'
OR Posts.Post_creator = 'AAAA'
But with this sql I don't really get the result, it's giving me multiple sample of same Topic_id and sometimes it just prints out all topics/posts.
So the tables I'm working with is:
Table 1 - Topics:
Table 2 - Posts
I would be grateful if someone more experienced would like to help me solve this PHP problem.
Thanks in advance
Try something like that :
SELECT DISTINCT *
FROM Topics
LEFT JOIN Posts ON Topics.Page_id = Posts.Page_id
where Topics.topic_creator = 'AAAA' OR Posts.Post_creator = 'AAAA'
You can join both tables with the column page_id so you could do something like this:
SELECT *
FROM Topics
INNER JOIN Posts ON Topics.Page_id = Posts.Page_id
WHERE Posts.Post_creator = 'the_name';
It's just an example, I hope it can help you.
Your question is basically not a php problem but rather an sql problem. Your SQL Join should look something like this
SELECT *
FROM Topics
LEFT JOIN Posts ON Topics.id = Posts.Topic_id
WHERE Topics.Topic_creator = 'AAA'
The best way to do this is with a UNION. One query returns all the topics that the user created, the other returns all the topics that the user posted in.
SELECT *
FROM Topics
WHERE Creator = 'AAA'
UNION
SELECT DISTINCT t.*
FROM Topics AS t
JOIN Posts AS p ON p.Topic_id = t.id
WHERE t.Creator != 'AAA'
AND p.Post_creator = 'AAA'
Also, notice that the second query only selects t.*, since you just want topic information, not information about all his posts. And DISTINCT prevents it from returning a row for each of his posts in the topic.
This will do what you want:
select * from Topics t
join Posts p
on t.id = p.Topic_id
where t.Topic_creator = 'AAA'
or p.Post_creator = 'AAA'
Make sure you have indexes on t.id, p.Topic_id, t.Topic_creator and p.Post_creator
try this
SELECT * FROM Topics t LEFT JOIN Posts p ON t.topic_creator = p.Post_creator
Related
Short setup
consider the following.
SELECT forum_category.groupid,
forum_category.categoryid,
forum_category.categoryname,
forum_category.categorydescription,
forum_category.category_url,
forum_category.accesslevel ,
COUNT(DISTINCT forum_topic.topicid) AS topics ,
COUNT(DISTINCT forum_post.postid) AS posts
FROM forum_category
INNER JOIN forum_topic ON forum_topic.categoryid=forum_category.categoryid
INNER JOIN forum_post ON forum_post.topicid=forum_topic.topicid
WHERE groupid = 1
result
This gives me actually one result, while i expect multiple rows (in this case 2) to come back. What am I missing here?
I have this model of table
I want to select all users WHERE tags (users_tags) are in tags setting (s_users_tag) of a specific user
I don't know how to do that.
I think is with this code
WHERE (req) IN (SELECT tags.name FROM `tags` INNER JOIN `s_users_tags` ON tags.id = s_users_tags.tag_id WHERE users_tags.user_uuid = "uuid of specific user"
But I don't know how write the first request or the first mumber (req)
Thank you.
I have found an answer for my problem
SELECT *
FROM users
WHERE exists (select * from `tags`
inner join `users_tags` on `tags`.`id` = `users_tags`.`tag_id`
where `users`.`uuid` = `users_tags`.`user_uuid` and tags.`id` in (1,2,4))
Where (1,2,4) come for an other request
I am not sure what you are asking so I will answer the question I think you are asking:
I want to find all users who have at least one tag that is both a users_tag and a s_users_tag.
SELECT * FROM users
INNER JOIN users_tags ON users_tags.user_uuid = users.uuid
INNER JOIN s_users_tags on s_users_tags.user_uuid = users.uuid
WHERE users_tags.tag_id=s_users_tags.tag_id
Well as everyone go for his little solution i try too :|
WITH USER_TAGGED AS (SELECT s_user_tags.user_uuid FROM user
JOIN users_tags ON users_tags.iuser_uuid = user.uuid
JOIN s_user_tags ON s_user_tags.tag_id = users_tags.tag_id
WHERE user.uuid = "uuid of specifi user")
SELECT * FROM user
JOIN USER_TAGGED ON user.uuid = USER_TAGGED.user_uuid
But i think we all better understand with sample of data from every table.
Can you tell us what is exactly s_user_tags please
I have the following query:
SELECT PKID, QuestionText, Type
FROM Questions
WHERE PKID IN (
SELECT FirstQuestion
FROM Batch
WHERE BatchNumber IN (
SELECT BatchNumber
FROM User
WHERE RandomString = '$key'
)
)
I've heard that sub-queries are inefficient and that joins are preferred. I can't find anything explaining how to convert a 3+ tier sub-query to join notation, however, and can't get my head around it.
Can anyone explain how to do it?
SELECT DISTINCT a.*
FROM Questions a
INNER JOIN Batch b
ON a.PKID = b.FirstQuestion
INNER JOIN User c
ON b.BatchNumber = c.BatchNumber
WHERE c.RandomString = '$key'
The reason why DISTINCT was specified is because there might be rows that matches to multiple rows on the other tables causing duplicate record on the result. But since you are only interested on records on table Questions, a DISTINCT keyword will suffice.
To further gain more knowledge about joins, kindly visit the link below:
Visual Representation of SQL Joins
Try :
SELECT q.PKID, q.QuestionText, q.Type
FROM Questions q
INNER JOIN Batch b ON q.PKID = b.FirstQuestion
INNER JOIN User u ON u.BatchNumber = q.BatchNumber
WHERE u.RandomString = '$key'
select
q.pkid,
q.questiontext,
q.type
from user u
join batch b
on u.batchnumber = b.batchnumber
join questions q
on b.firstquestion = q.pkid
where u.randomstring = '$key'
Since your WHERE clause filters on the USER table, start with that in the FROM clause. Next, apply your joins backwards.
In order to do this correctly, you need distinct in the subquery. Otherwise, you might multiply rows in the join version:
SELECT q.PKID, q.QuestionText, q.Type
FROM Questions q join
(select distinct FirstQuestion
from Batch b join user u
on b.batchnumber = u.batchnumber and
u.RandomString = '$key'
) fq
on q.pkid = fq.FirstQuestion
As to whether the in or join version is better . . . that depends. In some cases, particularly if the fields are indexed, the in version might be fine.
While working on a system I'm creating, I attempted to use the following query in my project:
SELECT
topics.id,
topics.name,
topics.post_count,
topics.view_count,
COUNT( posts.solved_post ) AS solved_post,
(SELECT users.username AS posted_by,
users.id AS posted_by_id
FROM users
WHERE users.id = posts.posted_by)
FROM topics
LEFT OUTER JOIN posts ON posts.topic_id = topics.id
WHERE topics.cat_id = :cat
GROUP BY topics.id
":cat" is bound by my PHP code as I'm using PDO. 2 is a valid value for ":cat".
That query though gives me an error: "#1241 - Operand should contain 1 column(s)"
What stumps me is that I would think that this query would work no problem. Selecting columns, then selecting two more from another table, and continuing on from there. I just can't figure out what the problem is.
Is there a simple fix to this, or another way to write my query?
Your subquery is selecting two columns, while you are using it to project one column (as part of the outer SELECT clause). You can only select one column from such a query in this context.
Consider joining to the users table instead; this will give you more flexibility when selecting what columns you want from users.
SELECT
topics.id,
topics.name,
topics.post_count,
topics.view_count,
COUNT( posts.solved_post ) AS solved_post,
users.username AS posted_by,
users.id AS posted_by_id
FROM topics
LEFT OUTER JOIN posts ON posts.topic_id = topics.id
LEFT OUTER JOIN users ON users.id = posts.posted_by
WHERE topics.cat_id = :cat
GROUP BY topics.id
In my case, the problem was that I sorrounded my columns selection with parenthesis by mistake:
SELECT (p.column1, p.column2, p.column3) FROM table1 p WHERE p.column1 = 1;
And has to be:
SELECT p.column1, p.column2, p.column3 FROM table1 p WHERE p.column1 = 1;
Sounds silly, but it was causing this error and it took some time to figure it out.
This error can also occur if you accidentally use commas instead of AND in the ON clause of a JOIN:
JOIN joined_table ON (joined_table.column = table.column, joined_table.column2 = table.column2)
^
should be AND, not a comma
This error can also occur if you accidentally use = instead of IN in the WHERE clause:
FOR EXAMPLE:
WHERE product_id = (1,2,3);
COUNT( posts.solved_post ) AS solved_post,
(SELECT users.username AS posted_by,
users.id AS posted_by_id
FROM users
WHERE users.id = posts.posted_by)
Well, you can’t get multiple columns from one subquery like that. Luckily, the second column is already posts.posted_by! So:
SELECT
topics.id,
topics.name,
topics.post_count,
topics.view_count,
posts.posted_by
COUNT( posts.solved_post ) AS solved_post,
(SELECT users.username AS posted_by_username
FROM users
WHERE users.id = posts.posted_by)
...
I got this error while executing a MySQL script in an Intellij console, because of adding brackets in the wrong place:
WRONG:
SELECT user.id
FROM user
WHERE id IN (:ids); # Do not put brackets around list argument
RIGHT:
SELECT user.id
FROM user
WHERE id IN :ids; # No brackets is correct
This error can also occur if you accidentally miss if function name.
for example:
set v_filter_value = 100;
select
f_id,
f_sale_value
from
t_seller
where
f_id = 5
and (v_filter_value <> 0, f_sale_value = v_filter_value, true);
Got this problem when I missed putting if in the if function!
Another place this error can happen in is assigning a value that has a comma outside of a string. For example:
SET totalvalue = (IFNULL(i.subtotal,0) + IFNULL(i.tax,0),0)
(SELECT users.username AS posted_by,
users.id AS posted_by_id
FROM users
WHERE users.id = posts.posted_by)
Here you using sub-query but this sub-query must return only one column.
Separate it otherwise it will shows error.
I also have the same issue in making a company database.
this is the code
SELECT FNAME,DNO FROM EMP
WHERE SALARY IN (SELECT MAX(SALARY), DNO
FROM EMP GROUP BY DNO);
Here's what I want to do:
select tableB.column1 WHERE tableB.column2 = some_var
select tableA.column1 WHERE tableA.column2 was a result from step one.
Can this be done in one select? What's the best way to do this, especially performance-wise? I'm using PHP.
EDIT:
I have a conversation based messaging system. 1 convo table and 1 replies table. Replies table includes columns: responder and convo_id. To load convo I get all replies with that convo_id.
I want to use the convoId to get all responders to that convo, and go into usertable and select all the avatars of responders, then store the avatars in array and echo them out as needed.
Try the following:
select a.Column1
FROM tableA a
LEFT JOIN tableB b ON a.Column2 = b.Column1
You could also use subquery, but that's less performant.
You may want to try the following sql statement
SELECT u.avatar
FROM usertable u
JOIN replies r ON u.responder_id = r.responder_id
WHERE r.convo_id = 1234
this will get all the avatars of the users who participated in the conversation with id 1234
Here's what I decided to go with. It builds an array ($avatars) where keys are usernames and values are avatars.
$result = mysql_query("SELECT
DISTINCT users.avatar,replies.sender
FROM users
JOIN replies
ON users.username = replies.sender
WHERE replies.convo_id = '$convoID'
");
while($array = mysql_fetch_assoc($result)){
$avatars[$array['sender']] = $array['avatar'];
}