Hi and thanks in advance for your answer/s.
I have two tables, tracks(info on music tracks, title, lenght, cd_id..etc) and purchd_items(purchased tracks, cd_id, user_id..etc). I have this query:
function blue($id)
{
$user_id = $this->tank_auth->get_user_id();
$query = $this->db->query("SELECT tracks.id, tracks.track_id, tracks.cd_id, tracks.title, tracks.lenght, tracks.price, tracks.file, tracks.preview, tracks.hash, purchd_items.cd_id, purchd_items.name FROM tracks LEFT JOIN purchd_items ON tracks.cd_id = purchd_items.cd_id WHERE purchd_items.user_id = $user_id AND tracks.cd_id = $id GROUP BY tracks.title, purchd_items.name ORDER BY tracks.track_id");
return $query->result();
}
What I am trying to do check two tables for match and display all the info from tracks table as well as matching items from purchd_items table that will replace the entries from tracks table. If the user has already bought any tracks I want to display the download link instead of usual buy track link.Kind of like itunes, I guess.
I was sort of able to get this working using the query above but the number of items in the returned array was multiplied by the number of entries in the purchd_items table and I couldn't get rid of the duplicates.
Hope I am making sense here! Thank you!
I figured it out!
SELECT tracks.id, tracks.track_id, tracks.cd_id, tracks.title, tracks.lenght, tracks.price, tracks.file, tracks.preview, tracks.hash, purchd_items.cd_id, purchd_items.name FROM tracks LEFT JOIN purchd_items ON tracks.cd_id = purchd_items.cd_id AND purchd_items.name = tracks.title AND purchd_items.user_id = $user_id WHERE tracks.cd_id = $id ORDER BY tracks.id
Related
I am working on a private message app using CodeIgniter.
I have 3 tables:
conversations
conversations_messages
conversations_members.
I am trying to join the tables by matching the conversations ids and fetch all the messages for the user who's logged in.
This is the standard sql query
SELECT
'conversations','conversation_id',
'conversations','conversation_subject',
MAX('conversations_messages','message_date') AS 'conversation_last_reply'
FROM 'conversations'
LEFT JOIN 'conversations_messages' ON 'conversations'.'conversation_id' = 'conversations_messages'.'conversation_id'
INNER JOIN 'conversations_members' ON 'conversations'.'conversation_id' = 'conversations_members'.'conversation_id'
WHERE 'conversations_members', 'user_id' = $sender_id
AND 'conversations_members','conversation_deleted' = 0
GROUP BY 'conversations'.'conversation_id'
ORDER BY 'conversation_last_reply' DESC";
Its a big query, hence; I'm not sure how to convert it to CodeIgniter active records or simply make it run with the framework.
Any corrections would be appreciated too.
Try below code with CodeIgniter active record.
$this->db->select('conversations, conversation_id, conversation_subject');
$this->db->select_max('conversations_messages.message_date', 'conversation_last_reply');
$this->db->from('conversations');
// Joining with conversations_messages table
$this->db->join('conversations_messages','conversations.id=conversations_messages.conversation_id','left');
$this->db->join('conversations_members','conversations.id= conversations_members.conversation_id','inner');
$this->db->where('conversations_members.user_id',$sender_id);
$this->db->where('conversations_members.conversation_deleted','0');
$this->db->group_by('conversations.conversation_id');
$this->db->order_by('conversation_last_reply');
// Get the results from db
$query = $this->db->get();
// Result array contains the records selected
$result_array = $query->result_array();
Happy coding
Naseem
$this->db->select('conversations, conversation_id, conversation_subject');
$this->db->select_max('conversations_messages.message_date', 'conversation_last_reply');
$this->db->from('conversations');
// Joining with conversations_messages table
$this->db->join('conversations_messages','conversations.id=conversations_messages.conversation_id','left');
$this->db->join('conversations_members','conversations.id= conversations_members.conversation_id','inner');
$this->db->where('conversations_members.user_id',$sender_id);
$this->db->where('conversations_members.conversation_deleted','0');
$this->db->group_by('conversations.conversation_id');
$this->db->order_by('conversation_last_reply');
// Get the results from db
$query = $this->db->get();
// Result array contains the records selected
$result_array = $query->result_array();
Now the result is that it`s showing same post as many times as many photos it has.
What to limit times of viewing same news??
function get_all_news(){
$query = $this->db->select('news.*, news_photos.name as news_photo_name, news_photos.ext as news_photo_ext')->from('news')->join('news_photos', 'news.id = news_photos.id_news', 'left')->order_by("date", "desc")->get();
}
Try to use DISTINCT or a GROUP BY on news.id.
Here is my code:
<?php
$data = mysql_query("SELECT * FROM board") or die(mysql_error());
while($info = mysql_fetch_assoc( $data ))
{
if(!empty($info['user'])){
Print "".$info['user'].""; }
else {
}
myOtherQuery($info['id']);
}
function myOtherQuery($id) {
$result3 = mysql_query("SELECT COUNT(source_user_id) FROM likes
INNER JOIN pins ON pins.id = likes.pin_id
WHERE pins.board_id='$id'");
$c = mysql_result($result3, 0); // Cumulative tally of likes for board
{
Print "$c";
}
}
?>
The first part gets a users name and board details (board as in a photo album).
the second part joins that data with another sql table that counts the number of likes that board has.
Both are displayed as a name and a score represented by a number.
By default they are ordered by the date of creation. I'd like to be able to order them by the score. However, since the score is determined in the second part of the code, I don't know how to achieve it. Is it possible?
The solution is of course to query both at once in the first place, via a LEFT JOIN against a subquery returning the count per board_id:
SELECT
board.*,
/* Your PHP code will retrieve the likes count via this alias `numlikes` as in $info['numlikes'] */
numlikes
FROM
board
LEFT JOIN (
/* Subquery returns count per board_id */
SELECT pins.board_id, COUNT(source_user_id) AS numlikes
FROM
likes
INNER JOIN pins ON pins.id = likes.pin_id
GROUP BY pins.board_id
) likes ON board.id = likes.board_id
ORDER BY numlikes
It is nearly always significantly more efficient to perform a single query rather than n queries in a loop. You should strive to do so whenever possible.
You can do it in one query
SELECT board.*, count(likes.source_user_id) as score
FROM board
INNER JOIN pins
ON pins.board_id = board.id
INNER JOIN likes
ON pins.id = likes.pin_id
ORDER BY score
I have 3 tables 1 is an item table, one is a note table and the other is a note image table.
When a user views item details, all notes are picked up for that item (there is a item_id field in the note table)
The notes can have multiple images attached to them these are stored in flat file but are referenced by the "note image" table.
Now when displaying item details I run a query to get all notes for a item... simple enough, then these results are looped through to output them onto the page.
Problem now arises after adding images to notes, how would you go about querying all notes for a item say
SELECT * FROM notes WHERE item = 1
then how would you loop though the result array getting all note images for a note say
SELECT * FROM note_img WHERE note_img_noteid = 27
Its hurting my head a little because I can't visualize how to get the results and output them in PHP.
---EDIT---
Think I may of got it,
SELECT
d.door_note_id,
d.door_note_doorid,
d.door_note_timestamp,
d.door_note_editedtime,
d.door_note_text,
u.user_name AS created_by,
e.user_name AS edited_by,
i.door_img_id AS img_id,
i.door_img_url AS img_url
FROM
user u,
door_note d
LEFT JOIN
user e
ON
user_id = d.door_note_editeduserid
LEFT JOIN
door_img i
ON
door_img_noteid = d.door_note_id
WHERE
d.door_note_doorid = 214
AND
u.user_id = d.door_note_userid
Then I use this:
foreach ($result->result() as $row){
if(!isset($my_items[$row->door_note_id])){ //the note id becaoms a key
//here you set up an array for all the note details
$my_items[$row->door_note_id] = array('door_note_id'=>$row->door_note_id,
'door_note_doorid'=>$row->door_note_doorid,
'door_note_timestamp'=>$row->door_note_timestamp,
'door_note_editedtime'=>$row->door_note_editedtime,
'door_note_text'=>$row->door_note_text,
'created_by'=>$row->created_by,
'edited_by'=>$row->edited_by,
'images'=>array());
}
//if the note has any images add them to the images array for that note.
if(isset($row->img_url)){
$my_items[$row->door_note_id]['images'][] = $row->img_url;
}
}
Its very hard to know when you haven't post your relationships in a table but taking some assumptions
$query = "SELECT items.id as item_id, items.name as item_name, notes.id as note_id,
notes.description as note_description, note_image.image as note_image from notes
LEFT JOIN notes ON items.id = notes.item_id
LEFT JOIN note_image ON notes.id = note_image.note_img_noteid";
//this wil fetch all you items with description, notes and images, because item can have multiple notes, your result wil have multiple entires of the item. so you have to index correctly to use in views
$result = $this->db->query($query)
$my_items = array();
foreach ($result->result() as $row){
if(!isset($my_items[$row->item_id])){ //you item it becaoms a key
//here you set up an array for all your items
$my_items[$row->item_id] = array('item_name'=>$row->item_name, 'notes'=>array());
}
//here you stroe all images fro a note
if(!isset($my_items[$row->item_id]['notes'][$row->note_id])){
$my_items[$row->item_id]['notes'][$row->note_id] = array('note_description'=>$row->note_description, 'images'=>array());
}
$my_items[$row->item_id]['notes'][$row->note_id]['images'][] = $row->note_image;
}
I just need help refining this script to give me the values from both tables joined on the ID.
Basically I want the ID from both tables and then be able to get the other values from both tables based on the IDs (if need be) and display them in a loop.
The code I have is below but won't work.
$select = myQ("SELECT * FROM users a WHERE EXISTS (SELECT 1 FROM `videos` b WHERE a.id = b.id GROUP BY b.id HAVING count(*) > 1) ");
$i=0;
while ($row = myF($select)) {
$resultsLoopArray[$i]["videos.id"] = $row["id"];
$resultsLoopArray[$i]["videos.vid"] = $row["vid"];
$resultsLoopArray[$i]["users.username"] = $row["username"];
$i++;
}
if (isset($resultsLoopArray)) {
$tpl->Loop("searchResultsLoop", $resultsLoopArray);
}
For now all I need is the username from the users table, the id and video id from the video table.
Can someone help by chance?
you question is bit confusing me..
As for my understanding I am posting this soultion..
If you have two tables users , videos then .
$sql = "SELECT users.username , videos.* from users, videos where users.user_id = videos.user_id";
this query will fetch all record from users and videos table where user id is present in videos tables ...