SQL Join on user entered Title - mysql

I have a Blog and BlogCategories. A user can enter a category title, which will then pull all Blogs that have the category associated with it.
My set up is:
Blog:
ID
BlogCategoryID
BlogCategory:
ID
Title
My most recent attempt:
$sqlQuery = new SQLQuery();
$sqlQuery->select = array (
'*',
);
$sqlQuery->from = array (
"BlogEntry",
"LEFT JOIN BlogCategory ON BlogCategory.ID = '$category'"
);
$result = $sqlQuery->execute();
How do I achieve this?
Many thanks for your time.

You can use an INNER JOIN query as follow
SELECT *
FROM Blog a
INNER JOIN BlogCategory b
ON a.BlogCategoryID = b.ID
WHERE b.Title LIKE 'title_here'

Related

how to get value from one table which is not present in another that?

i have two table user table and book table.
user_id
1
2
3
4
5
book
user_id book_id
1 1
2 2
4 5
i want those record from user table which is not present book table . how should i do that ? i tried this code but is there any other efficient way ?
$cri_user = new CDbCriteria;
$cri_user->select = "t.user_id";
$cri_user->condition = "t.user_id NOT IN (select tu.user_id from books as tu group by tu.user_id)";
$model_user = User::model()->findAll($user);
if i get the solution in mysql form i can convert it into yii.
there are some more way to do the same:
method 1:
$sql = "select t.* from user t left join book b on b.user_id = t.user_id where b.user_id is null";
$records = Yii::app()->db->createCommand($sql)->queryAll();
print_r($records);
method 2:
$records = Yii::app()->db->createCommand()
->select('t.*')
->from('user t')
->leftJoin('book b', 'b.user_id = t.user_id')
->where('b.user_id is null')
->queryAll();
print_r($records);
in SQL you can write something like follows,
SELECT USER_ID FROM USER
WHERE NOT EXISTS (SELECT 1 FROM BOOKS
WHERE USER.USER_ID = BOOKS.USER_ID)

Selecting data for 1 specific user from multiple tables

So my database is composed of 5 tables with different columns for each one. The only column that keeps them all identified is the id. I'm trying to get the data for a specific user, but I only seem to get all users of the database instead.
This is what I have tried:
SELECT
ControlAccess.UserName,
ControlAccess.Pass,
Users.First_Name,
Users.Last_Name,
UserInfo.Age,
UserInfo.Country,
UserInfo.Address,
UserInfo.ZipCode,
Sessions.Matrix1,
Sessions.Matrix2,
Sessions.Result,
Operations.Operation,
FilePath.LocationFiles
FROM
MatrixUsers.UserInfo
INNER JOIN
MatrixUsers.Users
ON
UserInfo.idUserInfo = Users.idUsers = 1
INNER JOIN
MatrixUsers.ControlAccess
ON
ControlAccess.idControlAccess = UserInfo.idUserInfo = 1
INNER JOIN
MatrixUsers.Sessions
ON
Sessions.idSessions = ControlAccess.idControlAccess = 1
INNER JOIN
MatrixUsers.FilePath
ON
FilePath.idFilePath = Sessions.idSessions = 1
INNER JOIN
MatrixUsers.Operations
ON
Operations.idOperations = FilePath.idFilePath = 1;
I tried putting 1 at the end of each id to see if they matched, but I still get all the users.
I'm new to SQL and I'm only familiar with matching rows, but not choosing specific one.
Here are the columns of each table:
ControlAccess: {idControlAccess, UserName, Pass}
Sessions: {idSessions, Matrix1, Matrix2, Result}
FilePath: {idFilePath, LocationFiles}
Operations: {idOperation, Operation}
UserInfo: {idUserInfo, Age, Country, Address, ZipCode, Phone}
Use WHERE when you want specific user. for example, select user_id from table where user_id=the_specific_user_id . Follow this basic to built you complicate statement.
Just user where after all the joins
WHERE ANY_COLUMN_REFER_TO_USER_ID = YOUR_NEEDED_ID
so your full query would be like :
SELECT
ControlAccess.UserName,
ControlAccess.Pass,
Users.First_Name,
Users.Last_Name,
UserInfo.Age,
UserInfo.Country,
UserInfo.Address,
UserInfo.ZipCode,
Sessions.Matrix1,
Sessions.Matrix2,
Sessions.Result,
Operations.Operation,
FilePath.LocationFiles
FROM MatrixUsers.UserInfo
INNER JOIN MatrixUsers.Users
ON UserInfo.idUserInfo = Users.idUsers
INNER JOIN MatrixUsers.ControlAccess
ON ControlAccess.idControlAccess = UserInfo.idUserInfo
INNER JOIN MatrixUsers.Sessions
ON Sessions.idSessions = ControlAccess.idControlAccess
INNER JOIN MatrixUsers.FilePath
ON FilePath.idFilePath = Sessions.idSessions
INNER JOIN MatrixUsers.Operations
ON Operations.idOperations = FilePath.idFilePath
WHERE UserInfo.idUserInfo = 1

SQL join multiple times?

I am making a user status list of the following format "A like B's XXX". A and B are both registered users and have firstname and lastname and user id. How to join the status table with the user table twice to get the names of the two users? Thank you.
SELECT "SQACTION"."TIMECREATED",
"SQWORDLIST".*,
"SUBJECT"."FIRSTNAME" subject_fn,
"SUBJECT"."LASTNAME" subject_ln,
author.firstname author_fn,
author.lastname author_ln
FROM "SQACTION"
INNER JOIN "SQWORDLIST"
ON SQACTION.ACTION = SQWORDLIST.GUID
INNER JOIN "SQUSER" SUBJECT
ON SQACTION.SUBJECT = SUBJECT.GUID
LEFT JOIN SQDOCUMENT
ON SQACTION.ENTITY = SQDOCUMENT.GUID
LEFT JOIN SQUSER AUTHOR
ON SQDOCUMENT.AUTHORID = AUTHOR.GUID
WHERE (SUBJECT.GUID = 'B4D3BF632C0C4DB3AB01C8B284069D8F')
OR (SUBJECT.GUID IN ('67882AF3FA3C4254AF9A12CA0B0AB6E4',
'6A4B52FE233444838AACFE2AFFE4D38F',
'8CA3FB9061FF4710B51F1E398D3D1917'))
ORDER BY "TIMECREATED" DESC
This is what I have tried. Thank you.
You need to include the table name twice in the FROM clause, and use an alias so you can specify which fields from each instance of the table are used in the ON statement. You didn't provide enough details in your question to give an exact example, so here is something more general.
UserTable, with ID & Name
RegTable, with UserID, and SponsorID
select ut1.name as [User],
ut2.name as [Sponsor]
from UserTable ut1
inner join RegTable rt on ut1.id = rt.userid
inner join UserTable ut2 on rt.sponsorid = ut2.id
do you mean something like, status have two field links to user table?
select user_a.first_name as user_a_first_name, user_b.first_name as user_b_first_name, status.status_name
from status
left join users as user_a on user_a.id = status.user_from_id
left join users as user_b on user_b.id = status.user_to_id

Use multiple mysql joins

Database Scheme:
http://pastebin.com/aPXk1rMf
I'm want to select "post owner's uName" and "comment owner's uName" from "comments" table (i.e. I think I need cOwnerID>uName and pID>uID>uName) so that I can log some activities right after a comment is posted.
I tried to use MySQL joins in order to achieve that but I couldn't; so here's what I tried in vain.
$result = dbquery("INSERT INTO comments VALUES ('','$pID','$ownerID','$cmnt')"); // inserting a comment
$lastID = mysql_insert_id();
$res = dbquery("SELECT
users.username AS username
FROM `comments`
LEFT JOIN `users` on comments.cOwnerID = users.uID
WHERE (cID='$lastID')");
I think you have to use aliases for table users, because, actually, you will have two joins on this table : one for the post author and another for the comment's author.
Try something like this :
SELECT
commentAuthor.username AS commentauthor_username,
postAuthor.username AS postauthor_username
FROM `comments`
LEFT JOIN `users` AS commentAuthor on comments.cOwnerID = commentAuthor.uID
LEFT JOIN `posts` on posts.pId = comments.pID
LEFT JOIN `users` AS postAuthor on posts.uID = postAuthor.uID
WHERE (cID='$lastID')
SELECT users1.username, users2.username FROM Posts p
WHERE p.pID="$POST_OF_INTEREST"
LEFT JOIN users users1 ON users1.uID=p.uID
LEFT OUTER JOIN comments ON comments.pID=p.pID
LEFT OUTER JOIN users users2 ON users2.uID=comments.cOwnerID
Given a particular post ID, this will get the username of the person who posted and the username of each person who commented on that post (one row per comment).
SELECT Users.uName AS UserNamePost
, UserComment.uName AS UserNameComment
FROM Users
INNER JOIN Posts
ON Posts.uID = Users.uID;
INNER JOIN Comments
ON Comments.pID = Posts.pID ;
INNER JOIN Users AS UserComment
ON Comments.cOwnerID = UserComment.uID ;
This will aim to have the user that has posted the post and then join the user for all comments for the post
"SELECT
users.username AS username,
comments.cOwnerID AS commentOwner,
users.uID AS userID
FROM
comments
LEFT JOIN
users
ON
commentOwner = userID
WHERE
commentOwner = '{$lastID}'";

How to get 1 row from Table A and multiple rows from Table B

Table A is named "users" and Table B is named "comments". I want to select fields "user_id" and "user_name" from Table A and "date", "comment", "user_id" fields in Table B.
In a nutshell I am trying to get all the users and their comments with 1 query. Can the comments be put in its own array as there will be multiple comments like below or will it just be 1 comment and would have to run 2 queries?
Basic Example
user_id = 1
username = foo
comments[0]['date'] = 1234567890
comments[0]['comment'] = "Hello World!"
comments[1]['date'] = 1234567890
comments[1]['comment'] = "MySQL n00b"
Any basic examples would be great so I can get my head round it.
This would be a general query, to select all the comments of user_id = 1.
SELECT u.user_id, u.user_name, c.`date`, c.`comment`
FROM comments c
INNER JOIN users u ON c.user_id = u.user_id
WHERE c.user_id = 1
Assuming the user_id is 1, here is the code if you want an associative array with all user's comments. There is only one query, using JOIN statement.
$res = mysql_query("SELECT users.user_id as uid, users.user_name as username, comments.date, comments.comment, comments.user_id as cid FROM `users` LEFT JOIN comments on uid=cid WHERE cid = 1");
$i = 0;
while($arr = mysql_fetch_assoc($res))
{
$comments[$i]['date'] = $arr['date'];
$comments[$i]['comment'] = $arr['comment'];
$i++;
}
//var_dump($comments);
We call this JOIN. Better to take some sql/mysql tutorial or you get lost.