Query issue in Codeigniter - php

I want to random show 6 news/reviews on my front page but it shows the same content 6 times random but I will not have duplication of content. Here is the SQL query:
SELECT
anmeldelser.billed_sti ,
anmeldelser.overskrift ,
anmeldelser.indhold ,
anmeldelser.id ,
anmeldelser.godkendt
FROM
anmeldelser
LIMIT 0,6
UNION ALL
SELECT
nyheder.id ,
nyheder.billed_sti ,
nyheder.overskrift ,
nyheder.indhold ,
nyheder.godkendt
FROM nyheder
ORDER BY rand() LIMIT 0,6

showing my example with active record for simplicity,
try randomizing your offset instead of the order, while still limiting to 6
// get the total number of rows
$total_rows = $this->db->count_all_results('my_table');
// offset random point within the total rows
$offset = rand( 0 , $total_rows - 6 );
$q = $this->db->offset( $offset )->limit( 6 )->get( 'my_table' );
print_r( $q->result_array() );

//initialize query builder
$sql1=$sql2=$this->db;
$sql1->select('anmeldelser.billed_sti ,anmeldelser.overskrift ,anmeldelser.indhold ,anmeldelser.id ,anmeldelser.godkendt');
$sql1->from('anmeldelser');
$sql1->order_by('rand()');
$sql1->limit(3);
//get only sql string
$query1=$sql1->get_compiled_select();
$sql2->select('nyheder.id ,nyheder.billed_sti ,nyheder.overskrift ,nyheder.indhold ,nyheder.godkendt');
$sql2->from('nyheder');
$sql2->order_by('rand()');
$sql2->limit(3);
$query2=$sql2->get_compiled_select();
//combine two query
$query = $this->mydb->query("($query1) UNION ($query2)");
$result = $query->result();

I am assuming that you need to join a Two table by this comment of yours.
You didn't mention your foreign key so I am assuming that also.
It is also not clear that the column name of your tables are same or not.
So, I am posting an join query for your table in which I assume your foreign key and column name, so please correct that before using it.
Here is your query to join your table:
$query = $this->db
->select('an.billed_sti,an.overskrift,an.indhold,an.id,an.godkendt, ny.id as ny_id,ny.billed_sti as ny_billed_sti, ny.overskrift as ny_overskrift, ny.indhold as ny_indhold , ny.godkendt as ny_godkendt ')
->from('anmeldelser as an')
->join('nyheder as ny', 'ny.id_fk = an.id', 'left outer') // I am assuming here that the [id_fk] field is the foreign key
->limit(0, 6)
->order_by('puttablename.tablecolumn', 'asc') // Your you table name and column name by which you want to order, you can use [asc/desc] as your need
->get();
And If you want to UNION here is the solution for it.

Related

Mysql higher LIMIT offset very slow with join in PHP

I'm trying to change mySQL query for a faster data retrieval from the server. I have a table with more than 500,000 records but it takes forever to retrieve the data.
I want to change the query from
SELECT
loanapply.loanapplyId,
loanapply.loanAmount,
loanapply.email,
loanapply.approve,
loanapply.loanDate,
mkopakenya.name,
mkopakenya.idno,
mkopakenya.phoneNo,
mkopakenya.verification
FROM
loanapply
LEFT JOIN mkopakenya ON loanapply.email = mkopakenya.email
WHERE
loanapply.approve = 'ongoing'
AND loanapply.del = 'false'
AND loanapply.archive = 0
AND loanapply.loanDate = '$date'
GROUP BY
loanapply.loanapplyId,
loanapply.loanAmount,
loanapply.email,
loanapply.approve,
loanapply.loanDate,
mkopakenya.name,
mkopakenya.idno,
mkopakenya.phoneNo,
mkopakenya.verification
ORDER BY
loanapplyId DESC
LIMIT
$currentSize,
$limit
to
SELECT
loanapply.loanapplyId,
loanapply.loanAmount,
loanapply.email,
loanapply.approve,
loanapply.loanDate,
mkopakenya.name,
mkopakenya.idno,
mkopakenya.phoneNo,
mkopakenya.verification
FROM
loanapply
LEFT JOIN mkopakenya ON loanapply.email = mkopakenya.email AS data1
INNER JOIN (
SELECT
loanapply.loanapplyId
FROM
loanapply
LIMIT
$currentSize,
$limit
) AS data2 ON data1.loanapplyId = data2.loanapplyId
WHERE
loanapply.approve = 'ongoing'
AND loanapply.del = 'false'
AND loanapply.archive = 0
AND loanapply.loanDate = '$date'
ORDER BY
loanapplyId DESC
for faster data retrieval, The second query only returns blank values
for fast data retrival first you should check for valid indexes
be sure you have a proper composite index on loanapply eg:
create index myidx on loanapply ( loanDate, archive, del, approve, email )
and
table mkopakenya column ( email)
anyway (not for better perfomance but for proper use of SQL) you should not use group by without aggregation function (this behaviour is allowed for mysql version <5.7 but, by default, produce error for version >= 5.7) if you need distinct result use DISTINCT clause
SELECT DISTINCT loanapply.loanapplyId
, loanapply.loanAmount
, loanapply.email
, loanapply.approve
, loanapply.loanDate
, mkopakenya.name
, mkopakenya.idno
, mkopakenya.phoneNo
, mkopakenya.verification
FROM loanapply
LEFT JOIN mkopakenya ON loanapply.email = mkopakenya.email
WHERE loanapply.approve='ongoing'
AND loanapply.del='false'
AND loanapply.archive=0
AND loanapply.loanDate='$date'
ORDER BY loanapplyId DESC LIMIT $currentSize, $limit

How can I order the results of an SQL query by the count of another table based on a shard ID?

I have an SQL query that fetches posts from a database. Everything works fine, but now I need to order the results by the number of comments each post has. The comments are on a separate table and they have a post_id column that links it to the post. I need to order the posts by the count of the comments table based on a shard ID? I have tried everything but every time I try to add something to my query it stops running completely and leaves my page blank. I need help to know where to put the other JOIN statement. This is my query:
$union = "UNION ALL
(
SELECT DISTINCT wallposts.p_id,wallposts.is_profile_notes,wallposts.times_viewed,wallposts.columnTimesShared,
wallposts.marked,wallposts.secure_id,wallposts.reshared,wallposts.group_id,
wallposts.totaluploads,wallposts.WallUploadID,wallposts.type,
wallposts.value,wallposts.media,wallposts.youtube,wallposts.post_type,
wallposts.privacy,wallposts.tagedpersons,wallposts.with_friends_tagged,wallposts.emotion_head,wallposts.selected_emotion,wallposts.title,
wallposts.url,wallposts.description,wallposts.cur_image,
wallposts.uip,wallposts.likes,wallposts.userid,
wallposts.posted_by,wallposts.post as postdata,wallusers.*,
UNIX_TIMESTAMP() - wallposts.date_created AS TimeSpent,
PosterTable.mem_pic as posterPic, PosterTable.gender as posterGender,PosterTable.oauth_uid as poster_oauth_uid, PosterTable.username as posterUsername,
PosterTable.mem_fname as posterFname,PosterTable.work as posterWork,
PosterTable.mem_lname as posterLname,walllikes_track.id as PostLikeFound,wallposts.date_created
FROM
wallusers,wallusers as PosterTable, wallposts
LEFT JOIN walllikes_track
ON wallposts.p_id = walllikes_track.post_id AND walllikes_track.member_id = ".$user_id."
WHERE
wallusers.active = 1
AND
PosterTable.active = 1
AND
wallposts.group_id IN (".$groups.")
AND
wallposts.group_id != 0
AND
PosterTable.mem_id = wallposts.posted_by
AND
wallposts.marked < ".$this->flagNumber."
AND
wallusers.mem_id = wallposts.posted_by ) ";
The comments table is called wallcomments and it has a column called post_id. I know I need to use JOIN and COUNT but I don't know where to put it within my current code.
Try this query, I didn't run but i updated it.
SELECT wallposts.p_id,wallposts.is_profile_notes,wallposts.times_viewed,wallposts.columnTimesShared,
wallposts.marked,wallposts.secure_id,wallposts.reshared,wallposts.group_id,
wallposts.totaluploads,wallposts.WallUploadID,wallposts.type,
wallposts.value,wallposts.media,wallposts.youtube,wallposts.post_type,
wallposts.privacy,wallposts.tagedpersons,wallposts.with_friends_tagged,wallposts.emotion_head,wallposts.selected_emotion,wallposts.title,
wallposts.url,wallposts.description,wallposts.cur_image,
wallposts.uip,wallposts.likes,wallposts.userid,
wallposts.posted_by,wallposts.post as postdata,wallusers.*,
UNIX_TIMESTAMP() - wallposts.date_created AS TimeSpent,
PosterTable.mem_pic as posterPic, PosterTable.gender as posterGender,PosterTable.oauth_uid as poster_oauth_uid, PosterTable.username as posterUsername,
PosterTable.mem_fname as posterFname,PosterTable.work as posterWork,
PosterTable.mem_lname as posterLname,walllikes_track.id as PostLikeFound,wallposts.date_created
FROM
wallusers,wallusers as PosterTable, wallposts
WHERE
wallusers.active = 1
AND
PosterTable.active = 1
AND
wallposts.group_id IN (".$groups.")
AND
wallposts.group_id != 0
AND
PosterTable.mem_id = wallposts.posted_by
AND
wallposts.marked < ".$this->flagNumber."
AND
wallusers.mem_id = wallposts.posted_by ) " AND wallposts.p_id = walllikes_track.post_id AND walllikes_track.member_id = ".$user_id.";
A more readable query might look like this...
At least then we'd have a chance.
SELECT DISTINCT p.p_id
, p.is_profile_notes
, p.times_viewed
, p.columnTimesShared
, p.marked
, p.secure_id
, p.media...
FROM wallposts p...

Return list of member_number count in table

Consider the following table
I need to return a list in descending order with the count of the member_nr's who is appearing the most frequent in the table where tournament = 'EPL' AND ROUND = '12'
EXAMPLE
The script should return the following results:
I thought about the problem and my logic for the problem reads like this
STEP1: GET member_nr one by one
$sql = "SELECT DISTINCT *
FROM winners
WHERE tournament='$tour' AND round='$round'";
LOOP(){ //get 1 member number
$mem_nr = ['mem_nr']; //assign mem_nr to variable
STEP2: GET the count(number of times) ^ABOVE^ member number appears in table
"$sql="SELECT *, count(member_nr) as nrWins
FROM winners
where member_nr ='$memNr' and tournament='$tournament' AND round='$round'";"
LOOP(){//get count
STEP 3: DISPLAY DATA
echo $row=['nrWins'] //Display Number Wins
echo $memNr
}//END LOOP
}//END LOOP
My Problem:
The above does not seem very efficient to me, im looking for the shortest most efficient way to return the count of member numbers in table above, any ideas / suggestions are welcomed
Try something like this:
SELECT *, COUNT(*) AS `wins`
FROM `winners`
WHERE `tournament` = '$tournament'
AND `round` = '$round'
GROUP BY `member_nr`
ORDER BY `wins` DESC
select tournament,round,member_nr,count(*)
from table
where tournament = 'EPL'
and round = 12
group by tournament,round,member_nr
order by count(*) desc

Order by a SUM with multiple joins in codeigniter

Solution:
$query = $this->db->query("
SELECT *, SUM(views.times) AS sum
FROM channel
RIGHT JOIN video
ON channel.channel_id = video.channel_id
LEFT JOIN user
ON channel.user_id = user.user_id
LEFT JOIN views
ON channel.channel_id = views.channel_id
GROUP BY channel.channel_name
ORDER BY sum DESC
");
I have a query that returns a list of items.
function getfrontpage(){
$this->db->select('*');
$this->db->from('channel');
$this->db->join('video', 'channel.channel_id = video.channel_id' , 'right');
$this->db->join('user', 'channel.user_id = user.user_id');
$this->db->group_by("channel.channel_name");
$query = $this->db->get();
return $query->result();
}
Now i'm trying to order these with the SUM from another table, how can i achieve this?
Here is a picture from that table:
I want the results to be sorted by the SUM of the total of "times" for each "channel_id"
thanks in advance
I would suggest to run this through $this->db->query() instead.
It's nice to fetch simple values through CodeIgniters AR functions. But at some situations it's simply easier to build query strings instead.
In your case:
$query = $this->db->query("
SELECT channel_id, SUM(times) AS sum
FROM channel
GROUP BY channel_id
ORDER BY sum DESC
");
You can also escape most values through db->query()!
$this->db->query("
SELECT name
FROM table_name
WHERE id = ?
", array(1));
Isn't it as simple as $this->db->order_by("channel_id", "desc");? this orders the results by channel_id in descending order.
Assuming the table displayed in your question is called times_table, and has a key of user_id, channel_id, you can use the following code to join the times_table into your query so the "times" column is available to sort by.
$this->db->join("times_table", "times.user_id=channel.user_id, times.channel_id=channel.channel_id", "left");
// You've already grouped by channel_name, so grouping by channel_id is probably not necessary.
$this->db->order_by("SUM(times_table.times) DESC");
N.B. I just guessed the name of your displayed table is times_table.

Get total rows count of table

I want to get all rows count in my sql.
Table's first 2 columns look like that
My function looks like that
$limit=2;
$sql = "SELECT id,COUNT(*),dt,title,content FROM news ORDER BY dt DESC LIMIT " . $limit;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$stmt->bind_result($id, $total, $datetime, $title, $content);
$stmt->store_result();
$count = $stmt->num_rows;
if ($count > 0) {
while ($stmt->fetch()) {
Inside loop, I'm getting exact value of $total, but MySQL selects only 1 row - row with id number 1. (and $count is 1 too)
Tried this sql
SELECT id,dt,title,content FROM news ORDER BY dt DESC LIMIT 2
All goes well.
Why in first case it selects only 1 row? How can I fix this issue?
for ex my table has 5 rows. I want to get 2 of them with all fields, and get all rows count (5 in this case) by one query.
Remove COUNT(*). You will only ever get 1 row if you leave it in there.
Try adding GROUP BY dt if you want to use COUNT(*) (not sure why you're using it though).
EDIT
Fine, if you insist on doing it in a single call, here:
$sql = "SELECT id,(SELECT COUNT(id) FROM news) as total,dt,title,content FROM news ORDER BY dt DESC LIMIT " . $limit;
This is likely cause by the variable $limit being set to 1, or not being set and mysql defaulting to 1. Try changing your first line to
$sql = "SELECT id,COUNT(*),dt,title,content FROM news ORDER BY dt DESC";
EDIT
Change to:
$sql = "SELECT SQL_CALC_FOUND_ROWS,id,dt,title,content FROM news ORDER BY dt DESC LIMIT " . $limit;
And then use a second query with
SELECT FOUND_ROWS( )
to get the number of rows that match the query
This totally wreaks of a HW problem... why else besides a professor's retarded method to add complexity to a simple problem would you not want to run two queries?
anyways.... here:
SELECT id, (SELECT COUNT(*) FROM news) AS row_count, dt, title, content FROM news ORDER BY dt DESC LIMIT

Categories