Codeigniter SQL Join with multiple ON clauses? - sql

This is the SQL query displayed by codeigniter:
SELECT * FROM (status_updates) JOIN friend_connections ON ((
status_updates.userid=friend_connections.userid) OR
(status_updates.userid=friend_connections.friend_id)) WHERE
status_updates.enabled = "1" AND friend_connections.enabled = "1"
ORDER BY status_updates.date desc, status_updates.time desc LIMIT 20
The Codeigniter commands i used were:
$this->db->from('status_updates');
$this->db->order_by("status_updates.date", "desc");
$this->db->order_by("status_updates.time", "desc");
$this->db->limit(20);
$this->db->join('status_updates', '((status_updates.userid=friend_connections.userid) OR (status_updates.userid=friend_connections.friend_id))');
What i'm trying to do is select everything in two tables, status_updates and friend_connections. status_updates has the one column userid which i want to match with either userid or friend_id from friend_connections. Can someone tell me how i can do this please?
Also i noticed that codeigniter removes the two opening parentheses after the ON command in the above sql query.

Copy of your own answer in order to remove this from the unanswered stack:
$sql = "SELECT * FROM (status_updates) JOIN friend_connections ON ((status_updates.userid=friend_connections.userid) OR (status_updates.userid=friend_connections.friend_id)) WHERE status_updates.enabled = "1" AND friend_connections.enabled = "1" ORDER BY status_updates.date desc, status_updates.time desc LIMIT 20";
$status = $this->db->query($sql);
Please don't upvote. It's not my answer.

Related

SQL joining Thread with post issue how would you solve it

I need help
$sql = "SELECT
topics.topic_id,
topics.topic_subject,
topics.topic_date,
topics.topic_cat,
topics.topic_by,
topics.topic_open_close,
topics.topic_pin
FROM
topics
LEFT JOIN posts ON topics.topic_id = posts.post_topic_id
WHERE
topics.topic_cat = '". $_GET['id']."' AND topics.topic_pin = '0' ORDER BY posts.post_date DESC;
my SQL is ORDERING the Topics base on post date. the problem I'm having is that when I reply more than 1 time, lets say 3 replies, it shows 3 of the same threads.
the purpose I'm trying to archive with this Query is to bump up the thread by posting base on post_date. its doing the job. It's its just showing more than one thread.
how would you guys get write this Query to do the job?
Seems you are joining the posts table even thought you are not displaying some of its columns. But if you want to display 1 topic based on the latest post date, you can join the max(post_date) via subquery.
SELECT
topics.topic_id,
topics.topic_subject,
topics.topic_date,
topics.topic_cat,
topics.topic_by,
topics.topic_open_close,
topics.topic_pin
FROM topics
INNER JOIN
(SELECT max(post_date) post_date, post_topic_id FROM posts GROUP BY post_topic_id) t2 ON topics.topic_id = t2.post_topic_id
WHERE
topics.topic_cat = '". $_GET['id']."' AND topics.topic_pin = '0'
I solved it the long way. I needed to get it done. My plan was to make it short.
with a SQL Query.
I have a functions.php folder to run all my functions thru out the project.
so i created a function inside the functions.php to run all query and not having to repeat myself.
examp:
function query($sql, $conn){
$result = mysqli_query($conn, $sql);
if(!$result){
echo 'There is a Error in the SQL '. mysqli_error($conn);
}else{
return $result;
}
}
I added a column on Topics called "Topic_last_post_date". Every time someone post if the Query to post the post goes successfully it will execute the query to update the "Topic_last_post_date" on the assigned topic.
//posting Query ect ect..
if(!$result_of_query){
echo'Error';
}else{
$stamp_post_date_on_Topic = query("UPDATE topics SET topic_last_post_date = NOW() WHERE topic_id='".$topicid."' ", $conn);}
then I ended using the this query to display the topic DESC = Descending starting from the last to "Topic_last_post_date" posted.
$sql = "SELECT
topic_id,
topic_subject,
topic_date,
topic_cat,
topic_by,
topic_open_close,
topic_pin,
topic_last_post_date
FROM
topics
WHERE
topic_cat = '". $_GET['id']."' AND topic_pin = '0' ORDER BY topic_last_post_date DESC LIMIT ".$offset.", ".$no_of_records_per_page." ";
I hope it help someone! thanks guys

SQL COUNT FORM JOIN TABLES

I have the following sql command:
SELECT "USERNAME"."TOPICS".VALUE,
"USERNAME"."TOPICS".QID,
"USERNAME"."QUESTION".QRATING
FROM "USERNAME"."TOPICS" JOIN "USERNAME"."QUESTION"
ON "USERNAME"."TOPICS".QID = "USERNAME"."QUESTION".QID
AND "USERNAME"."TOPICS".VALUE = 'kia'
ORDER BY QRATING DESC
It works really well, but I want to count how many element returns. So I tried to use:
SELECT COUNT("USERNAME"."TOPICS".QID)
FROM "USERNAME"."TOPICS" JOIN "USERNAME"."QUESTION"
ON "USERNAME"."TOPICS".QID = "USERNAME"."QUESTION".QID
AND "USERNAME"."TOPICS".VALUE = 'kia'
ORDER BY QRATING DESC
But I get the error :
Column reference 'USERNAME.TOPICS.VALUE' is invalid. When the SELECT
list contains at least one aggregate then all entries must be valid
aggregate expressions.
What is the problem?
Hmmm. The ORDER BY should be getting the error, not the SELECT. However, your query would be much easier to understand using table aliases:
SELECT COUNT(t.QID)
FROM "USERNAME"."TOPICS" t JOIN
"USERNAME"."QUESTION" q
ON t.QID = q.QID AND t.VALUE = 'kia';
If the first query works, I see no reason why this would not (and your original without the ORDER BY should also work).

Mysql check limit 3 already in db

I wanna to make limit check. Primary - check if name already in last 3 lines. How to make?
$connect = db_connect();
$query = "SELECT * FROM `lastest` WHERE `name` LIKE '" .$name. "'";
$result = db_query($query, $connect);
if ($result) {
die('Already in db.'); }
Check is_exists column, this what i can suggest to you:
is_exists = 1 => Name exists
is_exists = 0 => Name doesn't exists
SELECT count(*) as is_exists,GROUP_CONCAT(`fname`) as a
FROM test.users
HAVING a LIKE "% YOUR_NAME %"
ORDER BY `fname` DESC
LIMIT 3 ;
Try it and let me know if it was help you
Don't hesitate ask any questions
Good luck
If your column id is "id" :
Googling "sql get last rows" (without quotes) leads to this page :
http://www.w3schools.com/sql/sql_func_last.asp
Pick up your db, and customize the request to get the 3 last lines. Then write a request querying a sub-request (this one who gets the 3 last lines) with your where statment...
So, assuming that your primary key is "id" :
SELECT COUNT(*)
FROM
(SELECT id, name
FROM lastest
ORDER BY id DESC
LIMIT 3) sub_lastest
WHERE `name` LIKE [name];

Codeigniter SQL Query Like in a group by field

I have a codeigniter code that produces this query:
SELECT other_categories.id as main_id, other_categories.name as main_full_name,
category_type as policy_no, GROUP_CONCAT(CONCAT_WS(" ",
other_cat_details.first_name,
other_cat_details.middle_name, other_cat_details.last_name)) as
other_full_name FROM
(`other_categories`) LEFT JOIN `other_category_details` ON
`other_category_details`.`other_category_id` = `other_categories`.`id` LEFT
JOIN `users` as other_cat_details ON `other_cat_details`.`id` =
`other_category_details`.`user_id` WHERE `category_type` = '2'
GROUP BY `main_id` ORDER BY `name` ASC LIMIT 10
Is there a way I can add another query where I can another query that will filter my data where other_full_name like variable $name_entered?
adding this before group by:
$this->db->like('other_full_name', $name);
Produces: Unknown column 'other_full_name' in 'where clause'
Please note that this is for wildcard search for a result that is a series of characters as what the query suggests. having clause would recognize other_full_name. I'm wondering if we can add 'like' to it.
Any help is highly appreciated. Please ask for clarification.
You can use a having clause:
having(other_full_name = $name)
In codeigniter, I think it would be:
$this->db->having('other_full_name like $name')
or some similar variant

Remove rows with one column duplicated (not 'distinct')

I'm using access, and I'm trying to write a query which will remove duplicates of one column. Here is my query so far:
SELECT
Drawings.DrawingID,
Players.NumOfGuessedAPainting,
Players.NumOfGuessedBPainting,
Players.NumOfGuessedCPainting,
Words.Word
FROM Words INNER JOIN
(Players INNER JOIN
(Drawings INNER JOIN
PlayersAndWords
ON Drawings.DrawingID = PlayersAndWords.DrawingID)
ON Players.PlayerID = PlayersAndWords.DrawingPlayerID)
ON Words.WordID = PlayersAndWords.WordID
WHERE ((Words.Word)='" + w + "')
ORDER BY (Players.NumOfGuessedAPainting
+Players.NumOfGuessedBPainting * 2
+Players.NumOfGuessedCPainting *3 ) DESC
The column Drawings.DrawingID might be duplicated, and I want the query to return only one row of each Drawings.DrawingID. "distinct" won't work here. I've read that group by might help but I couldn't figure how..
Could you help me?
Thanks in advance.
Just put these lined before ORDER BY line
GROUP BY
Drawings.DrawingID,
Players.NumOfGuessedAPainting,
Players.NumOfGuessedBPainting,
Players.NumOfGuessedCPainting,
Words.Word
Edited.